repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -3,10 +3,10 @@ /// HAL initialization error. #[derive(Debug, Copy, Clone, Eq, PartialEq)] pub enum HalError { - /// Error indicating that HAL has already been created once. + /// Error indicating that the requested operation was called before HAL creation. + HalNotCreated, + /// Error indicating that HAL was tried to be created twice. HalAlreadyCreated, - /// Error indicating that HAL has already been configured. - HalAlreadyConfigured, - /// Error indicating that the requested operation was called before HAL initialization. - HalNotInitializedYet, + /// Error indicating that system was tried to be initialized twice. + SystemAlreadyInitialized,
Shouldn't this be `HalAlreadyInitialized`?
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -20,88 +19,85 @@ use crate::user_peripherals::UserPeripherals; use internal_cell::InternalCell; use pac::{self, PMC, TC0}; -/// This lock will prevent from creating HAL instance twice in the system. -/// Since HAL manages the access to peripherals, creating and using multiple -/// instances of it could be unsafe. -static HAL_CREATION_LOCK: Mutex<bool> = Mutex::new(false); +/// Global system peripherals instance, used internally by HAL. +/// +/// # Safety +/// Mutex is not used here, because it would imply a critical section at every access to HAL. +/// Safety of this cell is managed by HAL instead, guaranteeing that undefined behavior will not occur. +static HAL_SYSTEM_PERIPHERALS: InternalCell<Option<SystemPeripherals>> = InternalCell::new(None); /// HAL implementation for Cortex-M based SAMV71 MCU. -pub struct Hal { - /// User-accessible peripherals. - user_peripherals: Option<UserPeripherals>, - /// System peripherals. - system_peripherals: InternalCell<SystemPeripherals>, -} +pub struct Hal {}
```suggestion pub struct Hal; ```
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -20,88 +19,85 @@ use crate::user_peripherals::UserPeripherals; use internal_cell::InternalCell; use pac::{self, PMC, TC0}; -/// This lock will prevent from creating HAL instance twice in the system. -/// Since HAL manages the access to peripherals, creating and using multiple -/// instances of it could be unsafe. -static HAL_CREATION_LOCK: Mutex<bool> = Mutex::new(false); +/// Global system peripherals instance, used internally by HAL. +/// +/// # Safety +/// Mutex is not used here, because it would imply a critical section at every access to HAL. +/// Safety of this cell is managed by HAL instead, guaranteeing that undefined behavior will not occur. +static HAL_SYSTEM_PERIPHERALS: InternalCell<Option<SystemPeripherals>> = InternalCell::new(None); /// HAL implementation for Cortex-M based SAMV71 MCU. -pub struct Hal { - /// User-accessible peripherals. - user_peripherals: Option<UserPeripherals>, - /// System peripherals. - system_peripherals: InternalCell<SystemPeripherals>, -} +pub struct Hal {} impl Hal { - /// Frequency for the time types (TODO) + /// Frequency of system timer. const TIMER_FREQ: u32 = 1_000_000; - /// Create new HAL instance from PAC peripherals. + /// Create system peripherals of HAL. /// - /// # Safety - /// This function is safe to call only once. - /// Subsequent calls will return an error, indicating that HAL instance has already been created. + /// This function steals PAC peripherals and returns a [`SystemPeripherals`] structure + /// containing peripherals used by [`SystemHal`] API implementation. /// - /// # Return - /// `Hal` if it's first call during the program lifetime, [`HalError::HalAlreadyCreated`] otherwise. - pub fn new() -> Result<Self, HalError> { - HAL_CREATION_LOCK.lock(|lock| { - if *lock { - return Err(HalError::HalAlreadyCreated); - } - - *lock = true; - Ok(()) - })?; - - let (user_peripherals, system_peripherals) = Hal::create_peripherals(); - Ok(Hal { - user_peripherals: Some(user_peripherals), - system_peripherals: InternalCell::new(system_peripherals), - }) - } - - /// Create peripherals for HAL + /// Some of these peripherals will be accessible only during HAL initialization + /// (between [`Hal::create`] and [`SystemHal::configure_hardware`] calls). /// /// # Safety - /// This function should be only called once inside `new`. + /// This function should be only called once inside [`Hal::create`]. /// Subsequent calls will return valid peripherals, but it's not possible to /// guarantee safety if multiple instances of peripherals are used in the system. - fn create_peripherals() -> (UserPeripherals, SystemPeripherals) { + fn create_system_peripherals() -> SystemPeripherals { let mcu_peripherals = unsafe { pac::Peripherals::steal() }; - let core_peripherals = unsafe { pac::CorePeripherals::steal() }; - let system_peripherals = SystemPeripherals { + SystemPeripherals { watchdog: Watchdog::new(mcu_peripherals.WDT), timer: Timer::new(mcu_peripherals.TC0), timer_ch0: None, timer_ch1: None, timer_ch2: None, pmc: Some(mcu_peripherals.PMC), - }; - - let user_peripherals = UserPeripherals { - chip_id: Some(mcu_peripherals.CHIPID), - timer_counter1: Some(mcu_peripherals.TC1), - timer_counter2: Some(mcu_peripherals.TC2), - timer_counter3: Some(mcu_peripherals.TC3), - pmc: None, - nvic: Some(core_peripherals.NVIC), - }; - - (user_peripherals, system_peripherals) + } } - /// Returns PAC peripherals for the user + /// Creates user peripherals instance. + /// + /// This function steals PAC peripherals and returns a [`UserPeripherals`] structure + /// containing all peripherals that are available to user via HAL drivers. + /// + /// Some of these peripherals are taken from SystemPeripherals structure, hence + /// this function should not be called before finishing HAL initialization (via + /// [`SystemHal::configure_hardware] function). + /// + /// This function executes in critical section, as it modifies HAL_SYSTEM_PERIPHERALS. /// /// # Safety - /// Can be called successfully only once. Subsequent calls will return None. + /// This function can be called successfully only once, after HAL initialization. + /// If called before that, or multiple times, it will return [`None`], as some of + /// the required peripherals will be missing. /// - /// # Return - /// [`UserPeripherals`] on first call, `None` on subsequent calls. - pub fn user_peripherals(&mut self) -> Option<UserPeripherals> { - self.user_peripherals.take() + /// # Returns + /// [`Some(UserPeripherals)`] if called for the first time after HAL initialization, + /// [`None`] otherwise. + pub fn create_user_peripherals() -> Option<UserPeripherals> {
Move public functions above the private ones
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -20,88 +19,85 @@ use crate::user_peripherals::UserPeripherals; use internal_cell::InternalCell; use pac::{self, PMC, TC0}; -/// This lock will prevent from creating HAL instance twice in the system. -/// Since HAL manages the access to peripherals, creating and using multiple -/// instances of it could be unsafe. -static HAL_CREATION_LOCK: Mutex<bool> = Mutex::new(false); +/// Global system peripherals instance, used internally by HAL. +/// +/// # Safety +/// Mutex is not used here, because it would imply a critical section at every access to HAL. +/// Safety of this cell is managed by HAL instead, guaranteeing that undefined behavior will not occur. +static HAL_SYSTEM_PERIPHERALS: InternalCell<Option<SystemPeripherals>> = InternalCell::new(None); /// HAL implementation for Cortex-M based SAMV71 MCU. -pub struct Hal { - /// User-accessible peripherals. - user_peripherals: Option<UserPeripherals>, - /// System peripherals. - system_peripherals: InternalCell<SystemPeripherals>, -} +pub struct Hal {} impl Hal { - /// Frequency for the time types (TODO) + /// Frequency of system timer. const TIMER_FREQ: u32 = 1_000_000; - /// Create new HAL instance from PAC peripherals. + /// Create system peripherals of HAL.
```suggestion /// Creates system peripherals of HAL. ```
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -110,49 +106,116 @@ impl SystemHal for Hal { type Duration = crate::time::TimerDurationU64<{ Hal::TIMER_FREQ }>; type Error = HalError; - fn configure_hardware(&mut self, config: SystemHardwareConfig) -> Result<(), HalError> { - // SAFETY: This is safe, because this is a single-core system, - // and no other references to system peripherals should exist. - let peripherals = unsafe { self.system_peripherals.as_mut_ref() }; + /// Initialize global HAL instance using PAC peripherals.
```suggestion /// Initializes global HAL instance using PAC peripherals. ```
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -110,49 +106,116 @@ impl SystemHal for Hal { type Duration = crate::time::TimerDurationU64<{ Hal::TIMER_FREQ }>; type Error = HalError; - fn configure_hardware(&mut self, config: SystemHardwareConfig) -> Result<(), HalError> { - // SAFETY: This is safe, because this is a single-core system, - // and no other references to system peripherals should exist. - let peripherals = unsafe { self.system_peripherals.as_mut_ref() }; + /// Initialize global HAL instance using PAC peripherals. + /// + /// Calling this function begins HAL initialization process. This process must be finished + /// by calling [`SystemHal::configure_hardware`]. Until then, no other HAL functions should + /// be called, as they will most likely fail. + /// + /// This function executes in critical section, as it modifies HAL_SYSTEM_PERIPHERALS. + /// + /// # Safety + /// This function is safe to call only once. + /// Subsequent calls will return an error, indicating that HAL instance has already been created. + /// + /// # Return + /// `()` on success, [`HalError::HalAlreadyCreated`] if called more than once. + fn create() -> Result<(), HalError> {
Is this necessary to have `fn create` and `fn configure_hardware` separate? If one has to be called after another, and `create` doesn't return anything it seems unnecessary.
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -8,7 +8,8 @@ use crate::drivers::{ }; /// System peripherals structure. These peripherals are represented as HAL drivers. -/// They are initialized on system init, and used directly by HAL to provide core functionality. +/// Some of these peripherals are available only during HAL initialization +/// (between Hal::create and SystemHal::configure_hardware calls).
```suggestion /// (between SystemHal::create and SystemHal::configure_hardware calls). ```
aerugo
github_2023
others
39
n7space
Glamhoth
@@ -50,10 +49,7 @@ static TIME_MANAGER: TimeManager = TimeManager::new(); /// This shouldn't be created by hand by the user or anywhere else in the code. /// It should be used as a [singleton](crate::aerugo::AERUGO) that acts as a system API, /// both for user and for the internal system parts. -pub struct Aerugo { - /// Hardware Access/Abstraction Layer. - hal: InternalCell<Option<Hal>>, -} +pub struct Aerugo {}
```suggestion pub struct Aerugo; ```
aerugo
github_2023
others
35
n7space
SteelPh0enix
@@ -0,0 +1,8 @@ +[package] +authors = ["Filip Demski <glamhoth@protonmail.com>"] +edition = "2021" +name = "x86-basic-execution"
change name
aerugo
github_2023
others
33
n7space
Glamhoth
@@ -0,0 +1,16 @@ +#!/bin/bash + +set -euo pipefail + +if [ $# -eq 0 ] +then + for d in testbins/test-hal-*/; do + pushd $d > /dev/null + cargo build + popd > /dev/null + done +else + pushd examples/$1/ > /dev/null + cargo build + popd > /dev/null +fi
```suggestion for d in testbins/test-hal-*/; do pushd $d > /dev/null cargo build popd > /dev/null done ```
aerugo
github_2023
others
33
n7space
Glamhoth
@@ -58,6 +58,18 @@ jobs: - name: cargo build run: cargo build -p aerugo --features ${{ matrix.FEATURES }} + build-hal-tests: + name: Build HAL integration tests + runs-on: ubuntu-latest + steps:
```suggestion runs-on: ubuntu-latest needs: [rustfmt, clippy, build] steps: ```
aerugo
github_2023
python
33
n7space
Glamhoth
@@ -0,0 +1,162 @@ +"""Module containing some boilerplate, common to all tests that use `calldwell-rs` library.""" +import logging +from typing import Any, Callable, Optional, Tuple + +from .gdb_client import GDBClient +from .rtt_client import RTTClient + +RTT_SECTION_SYMBOL_NAME = "_SEGGER_RTT" +"""Section name of RTT symbol. Hard-coded in `rtt_target` library."""
Shouldn't the docs be above the line they are documenting?
aerugo
github_2023
others
31
n7space
SteelPh0enix
@@ -0,0 +1,113 @@ +/// @SRS{ROS-BSP-010} +/// +/// Design Analisys is described in N7S-ROS-SVSR-001, chapter 6.2.
s/Analisys/Analysis
aerugo
github_2023
others
30
n7space
Glamhoth
@@ -0,0 +1,22 @@ +use assert_cmd::Command; +// use test_binary::build_test_binary; + +/// @SRS{ROS-FUN-BSP-TIC-020} +/// @SRS{ROS-FUN-BSP-TIC-030} +/// @SRS{ROS-FUN-BSP-TIC-040} +/// @SRS{ROS-FUN-BSP-TIC-050} +/// @SRS{ROS-FUN-BSP-TIC-060} +/// @SRS{ROS-FUN-BSP-TIC-070}
Add the test scenario from the `main.rs` here
aerugo
github_2023
others
30
n7space
Glamhoth
@@ -0,0 +1,22 @@ +use assert_cmd::Command; +// use test_binary::build_test_binary;
```suggestion ```
aerugo
github_2023
python
30
n7space
Glamhoth
@@ -77,11 +77,11 @@ def main(): # Default watchdog timeout is 16s. Watchdog in this test is set to 3s, but timeout must be # few seconds higher to compensate for communication delays and MCU clock inaccuracies. - gdb.wait_for_reset(timeout=5) + gdb.wait_for_reset(timeout=10) finish_test(ssh) if __name__ == "__main__": - # logging.basicConfig(level=logging.INFO)
Necessary?
aerugo
github_2023
python
30
n7space
Glamhoth
@@ -1,6 +1,6 @@ import os -# import logging +import logging
Necessary?
aerugo
github_2023
others
29
n7space
Glamhoth
@@ -0,0 +1,139 @@ +//! Library providing software testing utilities for microcontrollers. +//! Also provides a panic handler that works over RTT. +//! Part of Calldwell testing framework. + +#![cfg(all(target_arch = "arm", target_os = "none"))] +#![deny(missing_docs)] +#![deny(warnings)] +#![no_std] + +mod streams; + +use core::cell::RefCell; + +use critical_section::{CriticalSection, Mutex}; +use rtt_target::rtt_init; +use streams::{DownStream, UpStream}; + +/// RTT channel acting as standard input. +static RTT_IN: Mutex<RefCell<Option<DownStream>>> = Mutex::new(RefCell::new(None)); +/// RTT channel acting as standard output. +static RTT_OUT: Mutex<RefCell<Option<UpStream>>> = Mutex::new(RefCell::new(None)); + +/// Initializes Calldwell's I/O. Call as soon as possible in the program, +/// to make Calldwell's RTT facilities available. +/// +/// This function runs in a critical section. +#[inline(never)] +pub fn initialize() { + critical_section::with(|cs| { + let channels = rtt_init! { + up: { + 0: { + size: 1024 + name: "CalldwellStdout" + } + } + down: { + 0: { + size: 1024 + name: "CalldwellStdin" + } + } + }; + + let rtt_in = DownStream::new(channels.down.0); + let rtt_out = UpStream::new(channels.up.0); + RTT_IN.borrow(cs).replace(Some(rtt_in)); + RTT_OUT.borrow(cs).replace(Some(rtt_out)); + }); +} + +/// Calls provided functor with mutable Calldwell input stream reference. +/// Creates a critical section, and passes it to the functor as argument +/// along with the stream. +/// +/// # Generic arguments
```suggestion /// # Generic Parameters ```
aerugo
github_2023
others
29
n7space
Glamhoth
@@ -0,0 +1,139 @@ +//! Library providing software testing utilities for microcontrollers. +//! Also provides a panic handler that works over RTT. +//! Part of Calldwell testing framework. + +#![cfg(all(target_arch = "arm", target_os = "none"))] +#![deny(missing_docs)] +#![deny(warnings)] +#![no_std] + +mod streams; + +use core::cell::RefCell; + +use critical_section::{CriticalSection, Mutex}; +use rtt_target::rtt_init; +use streams::{DownStream, UpStream}; + +/// RTT channel acting as standard input. +static RTT_IN: Mutex<RefCell<Option<DownStream>>> = Mutex::new(RefCell::new(None)); +/// RTT channel acting as standard output. +static RTT_OUT: Mutex<RefCell<Option<UpStream>>> = Mutex::new(RefCell::new(None)); + +/// Initializes Calldwell's I/O. Call as soon as possible in the program, +/// to make Calldwell's RTT facilities available. +/// +/// This function runs in a critical section. +#[inline(never)] +pub fn initialize() { + critical_section::with(|cs| { + let channels = rtt_init! { + up: { + 0: { + size: 1024 + name: "CalldwellStdout" + } + } + down: { + 0: { + size: 1024 + name: "CalldwellStdin" + } + } + }; + + let rtt_in = DownStream::new(channels.down.0); + let rtt_out = UpStream::new(channels.up.0); + RTT_IN.borrow(cs).replace(Some(rtt_in)); + RTT_OUT.borrow(cs).replace(Some(rtt_out)); + }); +} + +/// Calls provided functor with mutable Calldwell input stream reference. +/// Creates a critical section, and passes it to the functor as argument +/// along with the stream. +/// +/// # Generic arguments +/// * `F` - Functor type, must accept two arguments: `&mut DownStream` and `CriticalSection`. +/// Can return a value of any type. +/// * `T` - Type of value returned from functor `f`. +/// +/// # Parameters +/// * `f` - Functor to call +/// +/// # Returns +/// Value returned from functor `f`. +pub fn with_rtt_in<F, T>(f: F) -> T +where + F: FnOnce(&mut DownStream, CriticalSection) -> T, +{ + critical_section::with(|cs| { + let mut rtt_in_ref = RTT_IN.borrow(cs).borrow_mut(); + let rtt_in = rtt_in_ref + .as_mut() + .expect("you must initialize Calldwell before using data streams"); + + f(rtt_in, cs) + }) +} + +/// Calls provided functor with mutable Calldwell output stream reference. +/// Creates a critical section, and passes it to the functor as argument +/// along with the stream. +/// +/// # Generic arguments
```suggestion /// # Generic Parameters ```
aerugo
github_2023
others
26
n7space
SteelPh0enix
@@ -380,12 +419,82 @@ impl InitApi for Aerugo { Ok(()) } - fn subscribe_tasklet_to_event<T, C, const COND_COUNT: usize>( + /// Subscribes a tasklet to events. + /// + /// Tasklet subscribes for emited events. After subscription specific events has to be enabled
```suggestion /// Tasklet subscribes for emited events. After subscription, specific events have to be enabled ```
aerugo
github_2023
others
25
n7space
Glamhoth
@@ -0,0 +1,227 @@ +//! Module with functionalities of timer's channel in waveform mode. + +use pac::tc0::tc_channel::CMR_WAVEFORM_MODE; + +use super::{ + waveform_config::{ + ComparisonEffect, CountMode, ExternalEventConfig, OutputSignalEffects, RcCompareEffect, + RcCompareEffectFlags, WaveformModeConfig, + }, + Channel, ChannelId, TcMetadata, Waveform, +}; + +/// Channel implementation for Waveform channel. +impl<Timer, ID> Channel<Timer, ID, Waveform> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Enables the channel. + pub fn enable(&self) { + self.registers_ref().ccr.write(|w| w.clken().set_bit()); + } + + /// Disables the channel. + pub fn disable(&self) { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + } + + /// Triggers the channel via software, starting it. + pub fn trigger(&self) { + self.registers_ref().ccr.write(|w| w.swtrg().set_bit()); + } + + /// Sets waveform mode configuration. Does a single write to configuration register. + pub fn configure(&self, config: WaveformModeConfig) { + let rc_event_flags: RcCompareEffectFlags = config.rc_compare_effect.into(); + + self.registers_ref().cmr_waveform_mode().write(|w| { + w.cpcstop() + .variant(rc_event_flags.stops) + .cpcdis() + .variant(rc_event_flags.disables) + .eevtedg() + .variant(config.external_event.edge.into()) + .eevt() + .variant(config.external_event.signal.into()) + .enetrg() + .variant(config.external_event.enabled) + .wavsel() + .variant(config.mode.into()) + .wave() + .set_bit() + .acpa() + .bits(config.tioa_effects.rx_comparison.id()) + .acpc() + .bits(config.tioa_effects.rc_comparison.id()) + .aeevt() + .bits(config.tioa_effects.external_event.id()) + .aswtrg() + .bits(config.tioa_effects.software_trigger.id()) + .bcpb() + .bits(config.tiob_effects.rx_comparison.id()) + .bcpc() + .bits(config.tiob_effects.rc_comparison.id()) + .beevt() + .bits(config.tiob_effects.external_event.id()) + .bswtrg() + .bits(config.tiob_effects.software_trigger.id()) + }); + } + + /// Returns the effect of RC Compare event on channel's counter state. + pub fn rc_compare_effect(&self) -> RcCompareEffect { + let reg = self.mode_register().read(); + + RcCompareEffectFlags { + stops: reg.cpcstop().bit_is_set(), + disables: reg.cpcdis().bit_is_set(), + } + .into() + } + + /// Sets the effect of RC Compare event on channel's counter state. + pub fn set_rc_compare_effect(&self, effect: RcCompareEffect) { + let flags: RcCompareEffectFlags = effect.into(); + + self.mode_register().modify(|_, w| { + w.cpcstop() + .variant(flags.stops) + .cpcdis() + .variant(flags.disables) + }); + } + + /// Returns current external event configuration. + pub fn external_event_config(&self) -> ExternalEventConfig { + let reg = self.mode_register().read(); + + ExternalEventConfig { + edge: reg.eevtedg().variant().into(), + signal: reg.eevt().variant().into(), + enabled: reg.enetrg().bit_is_set(), + } + } + + /// Sets current external event configuration. + pub fn set_external_event_config(&self, config: ExternalEventConfig) { + self.mode_register().modify(|_, w| { + w.eevtedg() + .variant(config.edge.into()) + .eevt() + .variant(config.signal.into()) + .enetrg() + .variant(config.enabled) + }); + } + + /// Returns current counting mode. + pub fn count_mode(&self) -> CountMode { + self.mode_register().read().wavsel().variant().into() + } + + /// Sets current counting mode. + pub fn set_count_mode(&self, mode: CountMode) { + self.mode_register() + .modify(|_, w| w.wavsel().variant(mode.into())); + } + + /// Sets TIOA event/trigger effects. + /// + /// # Safety + /// This function will panic if an unexpected value is read from timer's registers. + /// If this happens, that means the PAC is broken and there's nothing that can be done on + /// user side to avoid it, as that kind of situation should never happen on correctly working + /// hardware. See `ComparisonEffect::from_id`for details about + /// value conversion. + pub fn tioa_effects(&self) -> OutputSignalEffects { + let reg = self.mode_register().read(); + let panic_message = "invalid comparison effect ID read from TC registers"; + + OutputSignalEffects { + rx_comparison: ComparisonEffect::from_id(reg.acpa().variant() as u8) + .expect(panic_message), + rc_comparison: ComparisonEffect::from_id(reg.acpc().variant() as u8) + .expect(panic_message), + external_event: ComparisonEffect::from_id(reg.aeevt().variant() as u8) + .expect(panic_message), + software_trigger: ComparisonEffect::from_id(reg.aswtrg().variant() as u8) + .expect(panic_message), + } + } + + /// Returns TIOA event/trigger effects.
Sets?
aerugo
github_2023
others
25
n7space
Glamhoth
@@ -0,0 +1,227 @@ +//! Module with functionalities of timer's channel in waveform mode. + +use pac::tc0::tc_channel::CMR_WAVEFORM_MODE; + +use super::{ + waveform_config::{ + ComparisonEffect, CountMode, ExternalEventConfig, OutputSignalEffects, RcCompareEffect, + RcCompareEffectFlags, WaveformModeConfig, + }, + Channel, ChannelId, TcMetadata, Waveform, +}; + +/// Channel implementation for Waveform channel. +impl<Timer, ID> Channel<Timer, ID, Waveform> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Enables the channel. + pub fn enable(&self) { + self.registers_ref().ccr.write(|w| w.clken().set_bit()); + } + + /// Disables the channel. + pub fn disable(&self) { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + } + + /// Triggers the channel via software, starting it. + pub fn trigger(&self) { + self.registers_ref().ccr.write(|w| w.swtrg().set_bit()); + } + + /// Sets waveform mode configuration. Does a single write to configuration register. + pub fn configure(&self, config: WaveformModeConfig) { + let rc_event_flags: RcCompareEffectFlags = config.rc_compare_effect.into(); + + self.registers_ref().cmr_waveform_mode().write(|w| { + w.cpcstop() + .variant(rc_event_flags.stops) + .cpcdis() + .variant(rc_event_flags.disables) + .eevtedg() + .variant(config.external_event.edge.into()) + .eevt() + .variant(config.external_event.signal.into()) + .enetrg() + .variant(config.external_event.enabled) + .wavsel() + .variant(config.mode.into()) + .wave() + .set_bit() + .acpa() + .bits(config.tioa_effects.rx_comparison.id()) + .acpc() + .bits(config.tioa_effects.rc_comparison.id()) + .aeevt() + .bits(config.tioa_effects.external_event.id()) + .aswtrg() + .bits(config.tioa_effects.software_trigger.id()) + .bcpb() + .bits(config.tiob_effects.rx_comparison.id()) + .bcpc() + .bits(config.tiob_effects.rc_comparison.id()) + .beevt() + .bits(config.tiob_effects.external_event.id()) + .bswtrg() + .bits(config.tiob_effects.software_trigger.id()) + }); + } + + /// Returns the effect of RC Compare event on channel's counter state. + pub fn rc_compare_effect(&self) -> RcCompareEffect { + let reg = self.mode_register().read(); + + RcCompareEffectFlags { + stops: reg.cpcstop().bit_is_set(), + disables: reg.cpcdis().bit_is_set(), + } + .into() + } + + /// Sets the effect of RC Compare event on channel's counter state. + pub fn set_rc_compare_effect(&self, effect: RcCompareEffect) { + let flags: RcCompareEffectFlags = effect.into(); + + self.mode_register().modify(|_, w| { + w.cpcstop() + .variant(flags.stops) + .cpcdis() + .variant(flags.disables) + }); + } + + /// Returns current external event configuration. + pub fn external_event_config(&self) -> ExternalEventConfig { + let reg = self.mode_register().read(); + + ExternalEventConfig { + edge: reg.eevtedg().variant().into(), + signal: reg.eevt().variant().into(), + enabled: reg.enetrg().bit_is_set(), + } + } + + /// Sets current external event configuration. + pub fn set_external_event_config(&self, config: ExternalEventConfig) { + self.mode_register().modify(|_, w| { + w.eevtedg() + .variant(config.edge.into()) + .eevt() + .variant(config.signal.into()) + .enetrg() + .variant(config.enabled) + }); + } + + /// Returns current counting mode. + pub fn count_mode(&self) -> CountMode { + self.mode_register().read().wavsel().variant().into() + } + + /// Sets current counting mode. + pub fn set_count_mode(&self, mode: CountMode) { + self.mode_register() + .modify(|_, w| w.wavsel().variant(mode.into())); + } + + /// Sets TIOA event/trigger effects.
Returns?
aerugo
github_2023
others
25
n7space
Glamhoth
@@ -0,0 +1,227 @@ +//! Module with functionalities of timer's channel in waveform mode. + +use pac::tc0::tc_channel::CMR_WAVEFORM_MODE; + +use super::{ + waveform_config::{ + ComparisonEffect, CountMode, ExternalEventConfig, OutputSignalEffects, RcCompareEffect, + RcCompareEffectFlags, WaveformModeConfig, + }, + Channel, ChannelId, TcMetadata, Waveform, +}; + +/// Channel implementation for Waveform channel. +impl<Timer, ID> Channel<Timer, ID, Waveform> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Enables the channel. + pub fn enable(&self) { + self.registers_ref().ccr.write(|w| w.clken().set_bit()); + } + + /// Disables the channel. + pub fn disable(&self) { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + } + + /// Triggers the channel via software, starting it. + pub fn trigger(&self) { + self.registers_ref().ccr.write(|w| w.swtrg().set_bit()); + } + + /// Sets waveform mode configuration. Does a single write to configuration register. + pub fn configure(&self, config: WaveformModeConfig) { + let rc_event_flags: RcCompareEffectFlags = config.rc_compare_effect.into(); + + self.registers_ref().cmr_waveform_mode().write(|w| { + w.cpcstop() + .variant(rc_event_flags.stops) + .cpcdis() + .variant(rc_event_flags.disables) + .eevtedg() + .variant(config.external_event.edge.into()) + .eevt() + .variant(config.external_event.signal.into()) + .enetrg() + .variant(config.external_event.enabled) + .wavsel() + .variant(config.mode.into()) + .wave() + .set_bit() + .acpa() + .bits(config.tioa_effects.rx_comparison.id()) + .acpc() + .bits(config.tioa_effects.rc_comparison.id()) + .aeevt() + .bits(config.tioa_effects.external_event.id()) + .aswtrg() + .bits(config.tioa_effects.software_trigger.id()) + .bcpb() + .bits(config.tiob_effects.rx_comparison.id()) + .bcpc() + .bits(config.tiob_effects.rc_comparison.id()) + .beevt() + .bits(config.tiob_effects.external_event.id()) + .bswtrg() + .bits(config.tiob_effects.software_trigger.id()) + }); + } + + /// Returns the effect of RC Compare event on channel's counter state. + pub fn rc_compare_effect(&self) -> RcCompareEffect { + let reg = self.mode_register().read(); + + RcCompareEffectFlags { + stops: reg.cpcstop().bit_is_set(), + disables: reg.cpcdis().bit_is_set(), + } + .into() + } + + /// Sets the effect of RC Compare event on channel's counter state. + pub fn set_rc_compare_effect(&self, effect: RcCompareEffect) { + let flags: RcCompareEffectFlags = effect.into(); + + self.mode_register().modify(|_, w| { + w.cpcstop() + .variant(flags.stops) + .cpcdis() + .variant(flags.disables) + }); + } + + /// Returns current external event configuration. + pub fn external_event_config(&self) -> ExternalEventConfig { + let reg = self.mode_register().read(); + + ExternalEventConfig { + edge: reg.eevtedg().variant().into(), + signal: reg.eevt().variant().into(), + enabled: reg.enetrg().bit_is_set(), + } + } + + /// Sets current external event configuration. + pub fn set_external_event_config(&self, config: ExternalEventConfig) { + self.mode_register().modify(|_, w| { + w.eevtedg() + .variant(config.edge.into()) + .eevt() + .variant(config.signal.into()) + .enetrg() + .variant(config.enabled) + }); + } + + /// Returns current counting mode. + pub fn count_mode(&self) -> CountMode { + self.mode_register().read().wavsel().variant().into() + } + + /// Sets current counting mode. + pub fn set_count_mode(&self, mode: CountMode) { + self.mode_register() + .modify(|_, w| w.wavsel().variant(mode.into())); + } + + /// Sets TIOA event/trigger effects. + /// + /// # Safety + /// This function will panic if an unexpected value is read from timer's registers. + /// If this happens, that means the PAC is broken and there's nothing that can be done on + /// user side to avoid it, as that kind of situation should never happen on correctly working + /// hardware. See `ComparisonEffect::from_id`for details about + /// value conversion. + pub fn tioa_effects(&self) -> OutputSignalEffects { + let reg = self.mode_register().read(); + let panic_message = "invalid comparison effect ID read from TC registers"; + + OutputSignalEffects { + rx_comparison: ComparisonEffect::from_id(reg.acpa().variant() as u8) + .expect(panic_message), + rc_comparison: ComparisonEffect::from_id(reg.acpc().variant() as u8) + .expect(panic_message), + external_event: ComparisonEffect::from_id(reg.aeevt().variant() as u8) + .expect(panic_message), + software_trigger: ComparisonEffect::from_id(reg.aswtrg().variant() as u8) + .expect(panic_message), + } + } + + /// Returns TIOA event/trigger effects. + pub fn set_tioa_effects(&self, effects: OutputSignalEffects) { + self.mode_register().modify(|_, w| { + w.acpa() + .bits(effects.rx_comparison.id()) + .acpc() + .bits(effects.rc_comparison.id()) + .aeevt() + .bits(effects.external_event.id()) + .aswtrg() + .bits(effects.software_trigger.id()) + }); + } + + /// Sets TIOB event/trigger effects.
Returns?
aerugo
github_2023
others
25
n7space
Glamhoth
@@ -0,0 +1,227 @@ +//! Module with functionalities of timer's channel in waveform mode. + +use pac::tc0::tc_channel::CMR_WAVEFORM_MODE; + +use super::{ + waveform_config::{ + ComparisonEffect, CountMode, ExternalEventConfig, OutputSignalEffects, RcCompareEffect, + RcCompareEffectFlags, WaveformModeConfig, + }, + Channel, ChannelId, TcMetadata, Waveform, +}; + +/// Channel implementation for Waveform channel. +impl<Timer, ID> Channel<Timer, ID, Waveform> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Enables the channel. + pub fn enable(&self) { + self.registers_ref().ccr.write(|w| w.clken().set_bit()); + } + + /// Disables the channel. + pub fn disable(&self) { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + } + + /// Triggers the channel via software, starting it. + pub fn trigger(&self) { + self.registers_ref().ccr.write(|w| w.swtrg().set_bit()); + } + + /// Sets waveform mode configuration. Does a single write to configuration register. + pub fn configure(&self, config: WaveformModeConfig) { + let rc_event_flags: RcCompareEffectFlags = config.rc_compare_effect.into(); + + self.registers_ref().cmr_waveform_mode().write(|w| { + w.cpcstop() + .variant(rc_event_flags.stops) + .cpcdis() + .variant(rc_event_flags.disables) + .eevtedg() + .variant(config.external_event.edge.into()) + .eevt() + .variant(config.external_event.signal.into()) + .enetrg() + .variant(config.external_event.enabled) + .wavsel() + .variant(config.mode.into()) + .wave() + .set_bit() + .acpa() + .bits(config.tioa_effects.rx_comparison.id()) + .acpc() + .bits(config.tioa_effects.rc_comparison.id()) + .aeevt() + .bits(config.tioa_effects.external_event.id()) + .aswtrg() + .bits(config.tioa_effects.software_trigger.id()) + .bcpb() + .bits(config.tiob_effects.rx_comparison.id()) + .bcpc() + .bits(config.tiob_effects.rc_comparison.id()) + .beevt() + .bits(config.tiob_effects.external_event.id()) + .bswtrg() + .bits(config.tiob_effects.software_trigger.id()) + }); + } + + /// Returns the effect of RC Compare event on channel's counter state. + pub fn rc_compare_effect(&self) -> RcCompareEffect { + let reg = self.mode_register().read(); + + RcCompareEffectFlags { + stops: reg.cpcstop().bit_is_set(), + disables: reg.cpcdis().bit_is_set(), + } + .into() + } + + /// Sets the effect of RC Compare event on channel's counter state. + pub fn set_rc_compare_effect(&self, effect: RcCompareEffect) { + let flags: RcCompareEffectFlags = effect.into(); + + self.mode_register().modify(|_, w| { + w.cpcstop() + .variant(flags.stops) + .cpcdis() + .variant(flags.disables) + }); + } + + /// Returns current external event configuration. + pub fn external_event_config(&self) -> ExternalEventConfig { + let reg = self.mode_register().read(); + + ExternalEventConfig { + edge: reg.eevtedg().variant().into(), + signal: reg.eevt().variant().into(), + enabled: reg.enetrg().bit_is_set(), + } + } + + /// Sets current external event configuration. + pub fn set_external_event_config(&self, config: ExternalEventConfig) { + self.mode_register().modify(|_, w| { + w.eevtedg() + .variant(config.edge.into()) + .eevt() + .variant(config.signal.into()) + .enetrg() + .variant(config.enabled) + }); + } + + /// Returns current counting mode. + pub fn count_mode(&self) -> CountMode { + self.mode_register().read().wavsel().variant().into() + } + + /// Sets current counting mode. + pub fn set_count_mode(&self, mode: CountMode) { + self.mode_register() + .modify(|_, w| w.wavsel().variant(mode.into())); + } + + /// Sets TIOA event/trigger effects. + /// + /// # Safety + /// This function will panic if an unexpected value is read from timer's registers. + /// If this happens, that means the PAC is broken and there's nothing that can be done on + /// user side to avoid it, as that kind of situation should never happen on correctly working + /// hardware. See `ComparisonEffect::from_id`for details about + /// value conversion. + pub fn tioa_effects(&self) -> OutputSignalEffects { + let reg = self.mode_register().read(); + let panic_message = "invalid comparison effect ID read from TC registers"; + + OutputSignalEffects { + rx_comparison: ComparisonEffect::from_id(reg.acpa().variant() as u8) + .expect(panic_message), + rc_comparison: ComparisonEffect::from_id(reg.acpc().variant() as u8) + .expect(panic_message), + external_event: ComparisonEffect::from_id(reg.aeevt().variant() as u8) + .expect(panic_message), + software_trigger: ComparisonEffect::from_id(reg.aswtrg().variant() as u8) + .expect(panic_message), + } + } + + /// Returns TIOA event/trigger effects. + pub fn set_tioa_effects(&self, effects: OutputSignalEffects) { + self.mode_register().modify(|_, w| { + w.acpa() + .bits(effects.rx_comparison.id()) + .acpc() + .bits(effects.rc_comparison.id()) + .aeevt() + .bits(effects.external_event.id()) + .aswtrg() + .bits(effects.software_trigger.id()) + }); + } + + /// Sets TIOB event/trigger effects. + /// + /// # Safety + /// This function will panic if an unexpected value is read from timer's registers. + /// If this happens, that means the PAC is broken and there's nothing that can be done on + /// user side to avoid it, as that kind of situation should never happen on correctly working + /// hardware. See `ComparisonEffect::from_id` for details about + /// value conversion. + pub fn tiob_effects(&self) -> OutputSignalEffects { + let reg = self.mode_register().read(); + let panic_message = "invalid comparison effect ID read from TC registers"; + + OutputSignalEffects { + rx_comparison: ComparisonEffect::from_id(reg.bcpb().variant() as u8) + .expect(panic_message), + rc_comparison: ComparisonEffect::from_id(reg.bcpc().variant() as u8) + .expect(panic_message), + external_event: ComparisonEffect::from_id(reg.beevt().variant() as u8) + .expect(panic_message), + software_trigger: ComparisonEffect::from_id(reg.bswtrg().variant() as u8) + .expect(panic_message), + } + } + + /// Returns TIOB event/trigger effects.
Sets?
aerugo
github_2023
others
23
n7space
SteelPh0enix
@@ -414,6 +512,22 @@ impl InitApi for Aerugo { Ok(()) } + + fn set_tasklet_conditions<T, C, const COND_COUNT: usize>( + &'static self, + tasklet_handle: &TaskletHandle<T, C, COND_COUNT>, + condition_set: BooleanConditionSet<COND_COUNT>, + ) -> Result<(), Self::Error> { + let tasklet = tasklet_handle.tasklet(); + + // SAFETY: This is safe as long as this function is called only during system initialization.
is this note somewhere where user can see it by reading documentation (attached to trait/function declaration)?
aerugo
github_2023
others
23
n7space
SteelPh0enix
@@ -0,0 +1,146 @@ +//! Boolean condition set. + +use heapless::Vec; + +use crate::aerugo::error::InitError; +use crate::boolean_condition::{BooleanCondition, BooleanConditionHandle}; +use crate::tasklet::TaskletPtr; + +/// Type of the set conditions list. +type ConditionsList<const N: usize> = Vec<&'static BooleanCondition, N>; + +/// Set of boolean conditions. +pub struct BooleanConditionSet<const N: usize> { + /// Type of the set. + set_type: BooleanConditionSetType, + /// Set conditions. + conditions: ConditionsList<N>, +} + +impl<const N: usize> BooleanConditionSet<N> { + /// Creates new condition set of given type. + /// + /// # Parameters + /// * `set_type` - Type of the condition set. + pub fn new(set_type: BooleanConditionSetType) -> Self { + BooleanConditionSet { + set_type, + conditions: ConditionsList::new(), + } + } + + /// Creates new condition set from array. + /// + /// # Parameters + /// * `condition` - Conditions array. + /// * `set_type` - Type of the condition set. + pub fn from_array( + conditions: [&BooleanConditionHandle; N], + set_type: BooleanConditionSetType, + ) -> Self { + BooleanConditionSet { + set_type, + conditions: ConditionsList::from_slice(&conditions.map(|handle| handle.condition())) + .unwrap(), + } + } + + /// Add a condition to the set. + /// + /// # Parameters + /// * `handle` - Handle to the condition. + pub fn add(&mut self, handle: &BooleanConditionHandle) -> Result<(), BooleanConditionSetError> { + match self.conditions.push(handle.condition()) { + Ok(_) => Ok(()), + Err(_) => Err(BooleanConditionSetError::SetFull), + } + } + + /// Registers tasklet to each condition in this set. + /// + /// # Parameter + /// * `tasklet` - Tasklet to register + /// + /// # Return + /// `()` if successful, `InitError` otherwise. + /// + /// # Safety + /// This is unsafe, because it mutably borrows the list of registered tasklets. + /// This is safe to call before the system initialization. + pub(crate) unsafe fn register_tasklet(&self, tasklet: TaskletPtr) -> Result<(), InitError> { + for cond in &self.conditions { + cond.register_tasklet(tasklet.clone())?; + } + + Ok(()) + } + + /// Evaluates value of this condition set. + pub(crate) fn evaluate(&self) -> bool { + match self.set_type { + BooleanConditionSetType::And => self.evaluate_and(), + BooleanConditionSetType::Or => self.evaluate_or(), + } + } + + /// Evaluates value of this condition set for `and` type. + fn evaluate_and(&self) -> bool { + for i in 0..N {
use `iter().all()` instead of raw loop? it's both more idiomatic way, as well as possibly more optimal
aerugo
github_2023
others
23
n7space
SteelPh0enix
@@ -0,0 +1,146 @@ +//! Boolean condition set. + +use heapless::Vec; + +use crate::aerugo::error::InitError; +use crate::boolean_condition::{BooleanCondition, BooleanConditionHandle}; +use crate::tasklet::TaskletPtr; + +/// Type of the set conditions list. +type ConditionsList<const N: usize> = Vec<&'static BooleanCondition, N>; + +/// Set of boolean conditions. +pub struct BooleanConditionSet<const N: usize> { + /// Type of the set. + set_type: BooleanConditionSetType, + /// Set conditions. + conditions: ConditionsList<N>, +} + +impl<const N: usize> BooleanConditionSet<N> { + /// Creates new condition set of given type. + /// + /// # Parameters + /// * `set_type` - Type of the condition set. + pub fn new(set_type: BooleanConditionSetType) -> Self { + BooleanConditionSet { + set_type, + conditions: ConditionsList::new(), + } + } + + /// Creates new condition set from array. + /// + /// # Parameters + /// * `condition` - Conditions array. + /// * `set_type` - Type of the condition set. + pub fn from_array( + conditions: [&BooleanConditionHandle; N], + set_type: BooleanConditionSetType, + ) -> Self { + BooleanConditionSet { + set_type, + conditions: ConditionsList::from_slice(&conditions.map(|handle| handle.condition())) + .unwrap(), + } + } + + /// Add a condition to the set. + /// + /// # Parameters + /// * `handle` - Handle to the condition. + pub fn add(&mut self, handle: &BooleanConditionHandle) -> Result<(), BooleanConditionSetError> { + match self.conditions.push(handle.condition()) { + Ok(_) => Ok(()), + Err(_) => Err(BooleanConditionSetError::SetFull), + } + } + + /// Registers tasklet to each condition in this set. + /// + /// # Parameter + /// * `tasklet` - Tasklet to register + /// + /// # Return + /// `()` if successful, `InitError` otherwise. + /// + /// # Safety + /// This is unsafe, because it mutably borrows the list of registered tasklets. + /// This is safe to call before the system initialization. + pub(crate) unsafe fn register_tasklet(&self, tasklet: TaskletPtr) -> Result<(), InitError> { + for cond in &self.conditions { + cond.register_tasklet(tasklet.clone())?; + } + + Ok(()) + } + + /// Evaluates value of this condition set. + pub(crate) fn evaluate(&self) -> bool { + match self.set_type { + BooleanConditionSetType::And => self.evaluate_and(), + BooleanConditionSetType::Or => self.evaluate_or(), + } + } + + /// Evaluates value of this condition set for `and` type. + fn evaluate_and(&self) -> bool { + for i in 0..N { + let condition = self.conditions[i]; + + if !condition.get_value() { + return false; + } + } + + true + } + + /// Evaluates value of this condition set for `or` type. + fn evaluate_or(&self) -> bool { + for i in 0..N { + let condition = self.conditions[i];
there should be equivalent to `iter().all()` that can be used here, if there is iterator support for our `Vec` type
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,108 @@ +//! Implementation of HAL Timer Counter driver. +pub mod channel; +pub mod channel_config; +mod tc_metadata; +pub mod timer_config; +pub mod timer_error; +pub mod waveform_config; + +use channel::*; +use tc_metadata::*; + +pub use channel::Channel; +pub use channel_config::*; +pub use timer_config::*; +pub use timer_error::*; +pub use waveform_config::*; + +use core::marker::PhantomData; + +use self::timer_error::TimerConfigurationError; + +/// Structure representing a Timer instance. +/// +/// # Generic parameters
```suggestion /// # Generic Parameters ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,108 @@ +//! Implementation of HAL Timer Counter driver. +pub mod channel; +pub mod channel_config; +mod tc_metadata; +pub mod timer_config; +pub mod timer_error; +pub mod waveform_config; + +use channel::*; +use tc_metadata::*; + +pub use channel::Channel; +pub use channel_config::*; +pub use timer_config::*; +pub use timer_error::*; +pub use waveform_config::*; + +use core::marker::PhantomData; + +use self::timer_error::TimerConfigurationError; + +/// Structure representing a Timer instance. +/// +/// # Generic parameters +/// * `TimerMetadata` - PAC timer counter instance metadata, see `TcMetadata` private trait. +pub struct Timer<TimerMetadata> { + /// Channel 0. + pub channel_0: Channel<TimerMetadata, Ch0, Disabled, NotConfigured>, + /// Channel 1. + pub channel_1: Channel<TimerMetadata, Ch1, Disabled, NotConfigured>, + /// Channel 2. + pub channel_2: Channel<TimerMetadata, Ch2, Disabled, NotConfigured>, + /// PhantomData for TC metadata. + _tc_peripheral: PhantomData<TimerMetadata>, +} + +impl<Instance> Timer<Instance> +where + Instance: TcMetadata, +{ + /// Returns a reference to Timer's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use, as long as there aren't multiple instances of [`Timer`] sharing the same registers, + /// and existing instances of [`Timer`] are created only with [`new`](Timer::new()) method + fn registers_ref(&self) -> &RegisterBlock {
Move to the end of the `impl` block
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,108 @@ +//! Implementation of HAL Timer Counter driver. +pub mod channel; +pub mod channel_config; +mod tc_metadata; +pub mod timer_config; +pub mod timer_error; +pub mod waveform_config; + +use channel::*; +use tc_metadata::*; + +pub use channel::Channel; +pub use channel_config::*; +pub use timer_config::*; +pub use timer_error::*; +pub use waveform_config::*; + +use core::marker::PhantomData; + +use self::timer_error::TimerConfigurationError; + +/// Structure representing a Timer instance. +/// +/// # Generic parameters +/// * `TimerMetadata` - PAC timer counter instance metadata, see `TcMetadata` private trait. +pub struct Timer<TimerMetadata> { + /// Channel 0. + pub channel_0: Channel<TimerMetadata, Ch0, Disabled, NotConfigured>, + /// Channel 1. + pub channel_1: Channel<TimerMetadata, Ch1, Disabled, NotConfigured>, + /// Channel 2. + pub channel_2: Channel<TimerMetadata, Ch2, Disabled, NotConfigured>, + /// PhantomData for TC metadata. + _tc_peripheral: PhantomData<TimerMetadata>, +} + +impl<Instance> Timer<Instance> +where + Instance: TcMetadata, +{ + /// Returns a reference to Timer's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use, as long as there aren't multiple instances of [`Timer`] sharing the same registers, + /// and existing instances of [`Timer`] are created only with [`new`](Timer::new()) method + fn registers_ref(&self) -> &RegisterBlock { + unsafe { &*Instance::REGISTERS } + } + + /// Create a new timer instance from PAC timer structure.
```suggestion /// Creates a new timer instance from PAC timer structure. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,108 @@ +//! Implementation of HAL Timer Counter driver. +pub mod channel; +pub mod channel_config; +mod tc_metadata; +pub mod timer_config; +pub mod timer_error; +pub mod waveform_config; + +use channel::*; +use tc_metadata::*; + +pub use channel::Channel; +pub use channel_config::*; +pub use timer_config::*; +pub use timer_error::*; +pub use waveform_config::*; + +use core::marker::PhantomData; + +use self::timer_error::TimerConfigurationError; + +/// Structure representing a Timer instance. +/// +/// # Generic parameters +/// * `TimerMetadata` - PAC timer counter instance metadata, see `TcMetadata` private trait. +pub struct Timer<TimerMetadata> { + /// Channel 0. + pub channel_0: Channel<TimerMetadata, Ch0, Disabled, NotConfigured>, + /// Channel 1. + pub channel_1: Channel<TimerMetadata, Ch1, Disabled, NotConfigured>, + /// Channel 2. + pub channel_2: Channel<TimerMetadata, Ch2, Disabled, NotConfigured>, + /// PhantomData for TC metadata. + _tc_peripheral: PhantomData<TimerMetadata>, +} + +impl<Instance> Timer<Instance> +where + Instance: TcMetadata, +{ + /// Returns a reference to Timer's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use, as long as there aren't multiple instances of [`Timer`] sharing the same registers, + /// and existing instances of [`Timer`] are created only with [`new`](Timer::new()) method + fn registers_ref(&self) -> &RegisterBlock { + unsafe { &*Instance::REGISTERS } + } + + /// Create a new timer instance from PAC timer structure. + /// + /// # Parameters + /// * `_instance` - PAC Timer Counter instance, consumed on construction to prevent + /// creation of duplicate Timer instances. + pub fn new(_instance: Instance) -> Self { + let tc = unsafe { &*Instance::REGISTERS }; + + Self { + channel_0: Channel::new(&tc.tc_channel0), + channel_1: Channel::new(&tc.tc_channel1), + channel_2: Channel::new(&tc.tc_channel2), + + _tc_peripheral: PhantomData, + } + } + + /// Triggers all channels, starting them if they are enabled. + pub fn trigger_all_channels(&self) { + self.registers_ref().bcr.write(|w| w.sync().set_bit()); + } + + /// Configures external clock signal source. This signal can be used as timer channel's input clock. + /// + /// # Parameters + /// * `clock` - Selected external clock that will be changed. + /// * `source` - External clock source that will be connected to selected clock. + /// + /// # Return + /// `Ok(())` if configuration arguments are valid, + /// `Err(TimerConfigurationError::InvalidClockSource)` if selected clock cannot be connected + /// to selected source (consult MCU manual for details). + /// + /// # Safety + /// This function directly modifies the registers of a timer in an unsafe manner, but values put in these + /// registers come from PAC, so they should be valid. + pub fn configure_external_clock_source( + &self, + clock: ExternalClock, + source: ExternalClockSource, + ) -> Result<(), TimerConfigurationError> { + let reg = &self.registers_ref().bmr; + let clock_source_id = match clock.id(source) { + Some(id) => id, + None => return Err(TimerConfigurationError::InvalidClockSource), + }; + + // SAFETY: `ExternalClockSource::to_clock_source_id` should return valid register value + // or perform early exit due to `?`, so this should be safe. + match clock { + ExternalClock::XC0 => reg.modify(|_, w| unsafe { w.tc0xc0s().bits(clock_source_id) }), + ExternalClock::XC1 => reg.modify(|_, w| unsafe { w.tc1xc1s().bits(clock_source_id) }), + ExternalClock::XC2 => reg.modify(|_, w| unsafe { w.tc2xc2s().bits(clock_source_id) }),
There's no `?` in the code below. Also, it have to be safe, just `should` is not enough. :]
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source.
```suggestion /// Returns currently used clock source. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register.
```suggestion /// Sets the value of channel's `C` register. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that.
```suggestion /// Reads channel's status register, and clean interrupt status flags after that. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration.
```suggestion /// Trait representing channel's ID /// /// It's type-level equivalent of ChannelNo enumeration. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait.
```suggestion /// Enumeration listing available channels. /// /// It's value-level equivalent of ChannelId trait. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed.
```suggestion /// Enables selected interrupts. /// /// State of other interrupts will not be changed. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be enabled. All interrupts set + /// to `true` will be enabled. + pub fn enable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().ier.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Disable selected interrupts. + /// State of other interrupts will not be changed.
```suggestion /// Disables selected interrupts. /// /// State of other interrupts will not be changed. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be enabled. All interrupts set + /// to `true` will be enabled. + pub fn enable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().ier.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Disable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be disabled. All interrupts set + /// to `true` will be disabled. + pub fn disable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().idr.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Returns the status (enabled/disabled) of channel's interrupts. + pub fn interrupts_masks(&self) -> ChannelInterrupts { + let masks = self.registers_ref().imr.read(); + + ChannelInterrupts { + counter_overflow: masks.covfs().bit(), + load_overrun: masks.lovrs().bit(), + ra_compare: masks.cpas().bit(), + rb_compare: masks.cpbs().bit(), + rc_compare: masks.cpcs().bit(), + ra_load: masks.ldras().bit(), + rb_load: masks.ldrbs().bit(), + external_trigger: masks.etrgs().bit(), + } + } + + /// Returns a reference to Channel's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use as long as Channel is created only using provided [`new`](Channel::new()) method via [`Timer`](super::Timer) instance, + /// as it guarantees that the pointer will be valid. + fn registers_ref(&self) -> &TC_CHANNEL { + unsafe { &*self.registers } + } + + /// Transform the channel into a type with different state and/or mode.
```suggestion /// Transforms the channel into a type with different state and/or mode. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be enabled. All interrupts set + /// to `true` will be enabled. + pub fn enable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().ier.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Disable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be disabled. All interrupts set + /// to `true` will be disabled. + pub fn disable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().idr.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Returns the status (enabled/disabled) of channel's interrupts. + pub fn interrupts_masks(&self) -> ChannelInterrupts { + let masks = self.registers_ref().imr.read(); + + ChannelInterrupts { + counter_overflow: masks.covfs().bit(), + load_overrun: masks.lovrs().bit(), + ra_compare: masks.cpas().bit(), + rb_compare: masks.cpbs().bit(), + rc_compare: masks.cpcs().bit(), + ra_load: masks.ldras().bit(), + rb_load: masks.ldrbs().bit(), + external_trigger: masks.etrgs().bit(), + } + } + + /// Returns a reference to Channel's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use as long as Channel is created only using provided [`new`](Channel::new()) method via [`Timer`](super::Timer) instance, + /// as it guarantees that the pointer will be valid. + fn registers_ref(&self) -> &TC_CHANNEL { + unsafe { &*self.registers } + } + + /// Transform the channel into a type with different state and/or mode. + /// + /// This is a helper function that allows to reduce state transition boilerplate to minimum. + /// + /// Rust compiler can deduce `Self` from function's return type, and transformation is basically a + /// no-op, so no code should be generated from this. This function is only to signalize the compiler + /// that we really want to change the type of an object. + /// + /// # Example + /// ```no_run + /// fn disable(self) -> Channel<Timer, ID, Disabled, Mode> { + /// // Do some logic to disable the timer here + /// // ... + /// + /// // Return channel with `State` changed to `Disabled` + /// // All generic arguments are deduced from this function's return type. + /// Channel::transform(self) + /// } + /// ``` + /// + /// # Parameters + /// * `channel` - Channel to be transformed. + const fn transform<NewState, NewMode>(channel: Channel<Timer, ID, NewState, NewMode>) -> Self { + Self { + registers: channel.registers, + _timer: PhantomData, + _id: PhantomData, + _state: PhantomData, + _mode: PhantomData, + } + } +} + +/// Channel implementation for disabled and not configured channels (default state). +impl<Timer, ID> Channel<Timer, ID, Disabled, NotConfigured> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Create new timer channel.
```suggestion /// Creates new timer channel. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be enabled. All interrupts set + /// to `true` will be enabled. + pub fn enable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().ier.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Disable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be disabled. All interrupts set + /// to `true` will be disabled. + pub fn disable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().idr.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Returns the status (enabled/disabled) of channel's interrupts. + pub fn interrupts_masks(&self) -> ChannelInterrupts { + let masks = self.registers_ref().imr.read(); + + ChannelInterrupts { + counter_overflow: masks.covfs().bit(), + load_overrun: masks.lovrs().bit(), + ra_compare: masks.cpas().bit(), + rb_compare: masks.cpbs().bit(), + rc_compare: masks.cpcs().bit(), + ra_load: masks.ldras().bit(), + rb_load: masks.ldrbs().bit(), + external_trigger: masks.etrgs().bit(), + } + } + + /// Returns a reference to Channel's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use as long as Channel is created only using provided [`new`](Channel::new()) method via [`Timer`](super::Timer) instance, + /// as it guarantees that the pointer will be valid. + fn registers_ref(&self) -> &TC_CHANNEL { + unsafe { &*self.registers } + } + + /// Transform the channel into a type with different state and/or mode. + /// + /// This is a helper function that allows to reduce state transition boilerplate to minimum. + /// + /// Rust compiler can deduce `Self` from function's return type, and transformation is basically a + /// no-op, so no code should be generated from this. This function is only to signalize the compiler + /// that we really want to change the type of an object. + /// + /// # Example + /// ```no_run + /// fn disable(self) -> Channel<Timer, ID, Disabled, Mode> { + /// // Do some logic to disable the timer here + /// // ... + /// + /// // Return channel with `State` changed to `Disabled` + /// // All generic arguments are deduced from this function's return type. + /// Channel::transform(self) + /// } + /// ``` + /// + /// # Parameters + /// * `channel` - Channel to be transformed. + const fn transform<NewState, NewMode>(channel: Channel<Timer, ID, NewState, NewMode>) -> Self { + Self { + registers: channel.registers, + _timer: PhantomData, + _id: PhantomData, + _state: PhantomData, + _mode: PhantomData, + } + } +} + +/// Channel implementation for disabled and not configured channels (default state). +impl<Timer, ID> Channel<Timer, ID, Disabled, NotConfigured> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Create new timer channel. + /// + /// # Parameters + /// * `channel` - Pointer to Timer Counter channel registers. + /// + /// # Safety + /// This function should be called only by [`Timer`](super::Timer), not by the user. + /// It's safe to use, as long as no duplicate channels (sharing the same registers) exist. + pub(super) fn new(channel: *const TC_CHANNEL) -> Channel<Timer, ID, Disabled, NotConfigured> { + Self { + registers: channel, + _timer: PhantomData, + _id: PhantomData, + _state: PhantomData, + _mode: PhantomData, + } + .synced_with_hardware() + } + + /// Resets the hardware state of the timer to correctly reflect it's typestate. + /// In this state, the function will disable timer's channel. + /// Our typestate should always be treated as "hard" guarantee, to which the hardware + /// state of timer's channel is always synchronized.
```suggestion /// Resets the hardware state of the timer to correctly reflect it's typestate. /// /// In this state, the function will disable timer's channel. /// Our typestate should always be treated as "hard" guarantee, to which the hardware /// state of timer's channel is always synchronized. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,456 @@ +//! Module representing timer counter's channel + +use core::marker::PhantomData; +use pac::tc0::tc_channel::TC_CHANNEL; + +use super::channel_config::*; +use super::TcMetadata; +use super::WaveformModeConfig; + +/// Structure representing a timer's channel. +pub struct Channel<Timer, ID, State, Mode> { + /// Timer channel's registers. + registers: *const TC_CHANNEL, + /// PhantomData for Timer type. + _timer: PhantomData<Timer>, + /// PhantomData for ID type. + _id: PhantomData<ID>, + /// PhantomData for State type. + _state: PhantomData<State>, + /// PhantomData for Mode type. + _mode: PhantomData<Mode>, +} + +/// Enumeration listing available channels. +/// It's value-level equivalent of ChannelId trait. +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum ChannelNo { + /// Channel 0. + Ch0 = 0, + /// Channel 1. + Ch1 = 1, + /// Channel 2. + Ch2 = 2, +} + +/// Trait representing channel's ID +/// It's type-level equivalent of ChannelNo enumeration. +pub trait ChannelId { + /// Numeric value od channel ID. + const ID: usize; +} + +/// Empty structure representing Channel 0 ID +pub struct Ch0; +/// Empty structure representing Channel 1 ID +pub struct Ch1; +/// Empty structure representing Channel 2 ID +pub struct Ch2; + +impl ChannelId for Ch0 { + const ID: usize = 0; +} + +impl ChannelId for Ch1 { + const ID: usize = 1; +} + +impl ChannelId for Ch2 { + const ID: usize = 2; +} + +/// Trait representing channel's state +pub trait ChannelState {} + +/// Empty structure representing timer's disabled state. +pub struct Disabled; +/// Empty structure representing timer's enabled state. +pub struct Enabled; + +impl ChannelState for Disabled {} +impl ChannelState for Enabled {} + +/// Trait representing channel's mode +pub trait ChannelMode {} + +/// Empty structure representing not configured channel. +pub struct NotConfigured; +/// Empty structure representing channel in Waveform mode. +pub struct WaveformMode; +/// Empty structure representing channel in Capture mode. +pub struct CaptureMode; + +impl ChannelMode for NotConfigured {} +impl ChannelMode for WaveformMode {} +impl ChannelMode for CaptureMode {} + +/// Channel implementation for all available states and modes +impl<Timer, ID, State, Mode> Channel<Timer, ID, State, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + State: ChannelState, + Mode: ChannelMode, +{ + /// Sets the clock source used by channel. + /// + /// # Parameters + /// * `clock` - New clock source for current channel. + pub fn set_clock_source(&self, clock: ChannelClock) { + match clock { + // Timer peripheral clock setting is configured via different register + // than the rest of the clocks. + ChannelClock::TimerPeripheralClock => { + self.registers_ref() + .emr + .modify(|_, w| w.nodivclk().set_bit()); + } + clock => { + // If an error happens here, it's a hard bug in HAL, there's no way for the user + // to handle this as it should be impossible to fail here. Hence, we panic. + let clock_id = clock.try_into().expect( + "internal HAL error - invalid clock tried to be converted into clock ID", + ); + + // This field is the same in Capture and Waveform mode. Hence, it can be changed in either. + self.registers_ref() + .cmr_waveform_mode() + .modify(|_, w| w.tcclks().variant(clock_id)) + } + } + } + + /// Get currently used clock source. + pub fn clock_source(&self) -> ChannelClock { + let is_timer_peripheral_clock_used = + self.registers_ref().emr.read().nodivclk().bit_is_set(); + + // This setting overrides clock configuration from CMR register. + if is_timer_peripheral_clock_used { + return ChannelClock::TimerPeripheralClock; + } + + self.registers_ref() + .cmr_waveform_mode() + .read() + .tcclks() + .variant() + .into() + } + + /// Returns current counter value from channel's register. + /// + /// # Implementation notes + /// CV register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn counter_value(&self) -> u16 { + self.registers_ref().cv.read().cv().bits() as u16 + } + + /// Returns current value of channel's `A` register. + /// + /// # Implementation notes + /// RA register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn ra(&self) -> u16 { + self.registers_ref().ra.read().ra().bits() as u16 + } + + /// Returns current value of channel's `B` register. + /// + /// # Implementation notes + /// RB register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rb(&self) -> u16 { + self.registers_ref().rb.read().rb().bits() as u16 + } + + /// Returns current value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// the returned value is casted to u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn rc(&self) -> u16 { + self.registers_ref().rc.read().rc().bits() as u16 + } + + /// Set the value of channel's `C` register. + /// + /// # Implementation notes + /// RC register is 32-bit, but all timer counters of SAMV71 MCUs are 16-bit, therefore + /// this function accepts only u16 to avoid confusion (or increase it, and make the user read MCU manual). + pub fn set_rc(&self, rc: u16) { + self.registers_ref().rc.write(|w| w.rc().variant(rc as u32)); + } + + /// Read channel's status register, and clean interrupt status flags after that. + /// + /// # Safety + /// **Reading status register will clear interrupt status flags**. If you are using interrupts, + /// make sure to be careful with this function in critical sections - if a timer interrupt will happen + /// during critical section, and you'll read the status flag, the interrupt handler that will execute after + /// critical section has ended will not know about events that happened between critical section start and + /// reading status register. Same scenario can happen in interrupt handlers, if timer interrupt has lower priority + /// than currently handled interrupt. + pub fn read_and_clear_status(&self) -> ChannelStatus { + let sr = self.registers_ref().sr.read(); + + ChannelStatus { + interrupts: ChannelInterrupts { + counter_overflow: sr.covfs().bit(), + load_overrun: sr.lovrs().bit(), + ra_compare: sr.cpas().bit(), + rb_compare: sr.cpbs().bit(), + rc_compare: sr.cpcs().bit(), + ra_load: sr.ldras().bit(), + rb_load: sr.ldrbs().bit(), + external_trigger: sr.etrgs().bit(), + }, + clock_enabled: sr.clksta().bit(), + tioa_state: sr.mtioa().bit(), + tiob_state: sr.mtiob().bit(), + } + } + + /// Enable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be enabled. All interrupts set + /// to `true` will be enabled. + pub fn enable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().ier.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Disable selected interrupts. + /// State of other interrupts will not be changed. + /// + /// # Parameters + /// * `interrupts` - Structure with interrupts to be disabled. All interrupts set + /// to `true` will be disabled. + pub fn disable_interrupts(&self, interrupts: ChannelInterrupts) { + self.registers_ref().idr.write(|w| { + w.covfs() + .variant(interrupts.counter_overflow) + .lovrs() + .variant(interrupts.load_overrun) + .cpas() + .variant(interrupts.ra_compare) + .cpbs() + .variant(interrupts.rb_compare) + .cpcs() + .variant(interrupts.rc_compare) + .ldras() + .variant(interrupts.ra_load) + .ldrbs() + .variant(interrupts.rb_load) + .etrgs() + .variant(interrupts.external_trigger) + }); + } + + /// Returns the status (enabled/disabled) of channel's interrupts. + pub fn interrupts_masks(&self) -> ChannelInterrupts { + let masks = self.registers_ref().imr.read(); + + ChannelInterrupts { + counter_overflow: masks.covfs().bit(), + load_overrun: masks.lovrs().bit(), + ra_compare: masks.cpas().bit(), + rb_compare: masks.cpbs().bit(), + rc_compare: masks.cpcs().bit(), + ra_load: masks.ldras().bit(), + rb_load: masks.ldrbs().bit(), + external_trigger: masks.etrgs().bit(), + } + } + + /// Returns a reference to Channel's registers. + /// + /// # Safety + /// This function dereferences a raw pointer. + /// It's safe to use as long as Channel is created only using provided [`new`](Channel::new()) method via [`Timer`](super::Timer) instance, + /// as it guarantees that the pointer will be valid. + fn registers_ref(&self) -> &TC_CHANNEL { + unsafe { &*self.registers } + } + + /// Transform the channel into a type with different state and/or mode. + /// + /// This is a helper function that allows to reduce state transition boilerplate to minimum. + /// + /// Rust compiler can deduce `Self` from function's return type, and transformation is basically a + /// no-op, so no code should be generated from this. This function is only to signalize the compiler + /// that we really want to change the type of an object. + /// + /// # Example + /// ```no_run + /// fn disable(self) -> Channel<Timer, ID, Disabled, Mode> { + /// // Do some logic to disable the timer here + /// // ... + /// + /// // Return channel with `State` changed to `Disabled` + /// // All generic arguments are deduced from this function's return type. + /// Channel::transform(self) + /// } + /// ``` + /// + /// # Parameters + /// * `channel` - Channel to be transformed. + const fn transform<NewState, NewMode>(channel: Channel<Timer, ID, NewState, NewMode>) -> Self { + Self { + registers: channel.registers, + _timer: PhantomData, + _id: PhantomData, + _state: PhantomData, + _mode: PhantomData, + } + } +} + +/// Channel implementation for disabled and not configured channels (default state). +impl<Timer, ID> Channel<Timer, ID, Disabled, NotConfigured> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Create new timer channel. + /// + /// # Parameters + /// * `channel` - Pointer to Timer Counter channel registers. + /// + /// # Safety + /// This function should be called only by [`Timer`](super::Timer), not by the user. + /// It's safe to use, as long as no duplicate channels (sharing the same registers) exist. + pub(super) fn new(channel: *const TC_CHANNEL) -> Channel<Timer, ID, Disabled, NotConfigured> { + Self { + registers: channel, + _timer: PhantomData, + _id: PhantomData, + _state: PhantomData, + _mode: PhantomData, + } + .synced_with_hardware() + } + + /// Resets the hardware state of the timer to correctly reflect it's typestate. + /// In this state, the function will disable timer's channel. + /// Our typestate should always be treated as "hard" guarantee, to which the hardware + /// state of timer's channel is always synchronized. + fn synced_with_hardware(self) -> Self { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + self + } +} + +/// Channel implementation for disabled channels. +impl<Timer, ID, Mode> Channel<Timer, ID, Disabled, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + Mode: ChannelMode, +{ + /// Enables the channel. + /// + /// Consumes current instance and returns new one, with `Enabled` state. + pub fn enable(self) -> Channel<Timer, ID, Enabled, Mode> { + self.registers_ref().ccr.write(|w| w.clken().set_bit()); + Channel::transform(self) + } + + /// Change channel's mode to Waveform mode. + /// + /// Consumes current instance and returns new one, in `Waveform` mode. + /// + /// # Parameters + /// * `config` - Waveform mode configuration. Can be changed later. + pub fn into_waveform_channel( + self, + config: WaveformModeConfig, + ) -> Channel<Timer, ID, Disabled, WaveformMode> { + let transformed_channel = Channel::transform(self); + transformed_channel.configure(config); + transformed_channel + } +} + +/// Channel implementation for enabled channels. +impl<Timer, ID, Mode> Channel<Timer, ID, Enabled, Mode> +where + Timer: TcMetadata, + ID: ChannelId, + Mode: ChannelMode, +{ + /// Disables the channel. + /// + /// Consumes current instance and returns new one, with `Disabled` state. + pub fn disable(self) -> Channel<Timer, ID, Disabled, Mode> { + self.registers_ref().ccr.write(|w| w.clkdis().set_bit()); + Channel::transform(self) + } + + /// Triggers the channel via software, starting it. + pub fn trigger(&self) { + self.registers_ref().ccr.write(|w| w.swtrg().set_bit()); + } +} + +/// Channel implementation for Waveform mode while disabled. +impl<Timer, ID> Channel<Timer, ID, Disabled, WaveformMode> +where + Timer: TcMetadata, + ID: ChannelId, +{ + /// Set waveform mode configuration.
```suggestion /// Sets waveform mode configuration. ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -0,0 +1,39 @@ +//! Module with PAC TC metadata implementation. +pub(super) use pac::tc0::RegisterBlock; +use pac::{Interrupt, TC0, TC1, TC2, TC3}; + +/// Amount of channels per timer instance. +const CHANNELS_COUNT_PER_TIMER: usize = 3; + +/// Trait for PAC timer counter instances. +/// This trait erases the type of TC instance, so it can be used as generic argument for [`Timer`](super::Timer)
```suggestion /// Trait for PAC timer counter instances. /// /// This trait erases the type of TC instance, so it can be used as generic argument for [`Timer`](super::Timer) ```
aerugo
github_2023
others
24
n7space
Glamhoth
@@ -5,6 +5,12 @@ use pac; /// Peripherals structure. /// These peripherals can be used to create HAL drivers in user code. pub struct UserPeripherals { - /// Chip ID. + /// Chip ID pub chip_id: Option<pac::CHIPID>, + /// Timer Counter 1 + pub timer_counter1: Option<pac::TC1>, + /// Timer Counter 2 + pub timer_counter2: Option<pac::TC2>, + /// Timer Counter 3 + pub timer_counter3: Option<pac::TC3>,
```suggestion /// Chip ID. pub chip_id: Option<pac::CHIPID>, /// Timer Counter 1. pub timer_counter1: Option<pac::TC1>, /// Timer Counter 2. pub timer_counter2: Option<pac::TC2>, /// Timer Counter 3. pub timer_counter3: Option<pac::TC3>, ```
aerugo
github_2023
others
11
n7space
SteelPh0enix
@@ -9,50 +9,77 @@ pub(crate) use self::message_queue_storage::QueueData; use heapless::Vec; +use crate::aerugo::AERUGO; use crate::aerugo::{ error::{InitError, RuntimeError}, Aerugo, }; +use crate::api::SystemApi; use crate::arch::Mutex; use crate::data_provider::DataProvider; +use crate::internal_cell::InternalCell; use crate::queue::Queue; -use crate::task::Task; +use crate::tasklet::TaskletPtr; + +/// List of tasklets registered to a queue +type TaskletList = Vec<TaskletPtr, { Aerugo::TASKLET_COUNT }>; /// Message queue used for exchanging data between tasklets. /// /// * `T` - Type of the stored data. /// * `N` - Size of the queue. -pub(crate) struct MessageQueue<'a, T, const N: usize> { +#[repr(C)]
why?
aerugo
github_2023
others
11
n7space
SteelPh0enix
@@ -23,27 +24,136 @@ pub(crate) type QueueData<T, const N: usize> = heapless::spsc::Queue<T, N>; /// * `N` - Size of the queue. pub struct MessageQueueStorage<T, const N: usize> { /// Marks whether this storage has been initialized. - _initialized: InternalCell<bool>, + initialized: InternalCell<bool>, /// Buffer for the queue structure. - _queue_buffer: InternalCell<QueueBuffer>, + queue_buffer: InternalCell<QueueBuffer>, /// Buffer for the queue data. - _queue_data: Mutex<QueueData<T, N>>, + queue_data: Mutex<QueueData<T, N>>, } impl<T, const N: usize> MessageQueueStorage<T, N> { /// Creates new storage. pub const fn new() -> Self { MessageQueueStorage { - _initialized: InternalCell::new(false), - _queue_buffer: InternalCell::new(QueueBuffer::new()), - _queue_data: Mutex::new(QueueData::new()), + initialized: InternalCell::new(false), + queue_buffer: InternalCell::new(QueueBuffer::new()), + queue_data: Mutex::new(QueueData::new()), } } + /// Returns initialization status of this storage. + pub fn is_initialized(&'static self) -> bool { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // the `init` function. + unsafe { *self.initialized.as_ref() } + } + /// Creates new handle to a queue allocated in this storage. /// /// Returns `Some(handle)` if this storage has been initialized, `None` otherwise. - pub fn create_queue_handle(&'static self) -> Option<MessageQueueHandle<T>> { - todo!() + pub fn create_handle(&'static self) -> Option<MessageQueueHandle<T, N>> { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // the `init` function. + match unsafe { *self.initialized.as_ref() } { + true => { + // SAFETY: This is safe because storage has been initialized. + let message_queue = unsafe { self.message_queue() }; + Some(MessageQueueHandle::new(message_queue)) + } + false => None, + } + } + + /// Initializes this storage. + /// + /// TODO: Returns + pub(crate) fn init(&'static self) -> Result<(), InitError> { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // this function. + if unsafe { *self.initialized.as_ref() } { + return Err(InitError::StorageAlreadyInitialized); + } + + let queue = MessageQueue::<T, N>::new(&self.queue_data); + + // SAFETY: This is safe, because it is borrowed mutably only here. It can be modified + // (initialized) only once, because it is guarded by the `initialized` field. No external + // borrow can be made before initialization. + unsafe { + // Because the `MessageQueue` structure is of a constant size, the `queue_buffer` field is + // statically allocated with enough memory for a 'placement new'. + let queue_buffer = + self.queue_buffer.as_mut_ref().as_mut_ptr() as *mut MessageQueue<T, N>; + core::ptr::write(queue_buffer, queue); + } + + // SAFETY: This is safe because it is only modified only here, and can't be externally
```suggestion // SAFETY: This is safe because it is modified only here, and can't be externally ```
aerugo
github_2023
others
11
n7space
SteelPh0enix
@@ -23,27 +24,136 @@ pub(crate) type QueueData<T, const N: usize> = heapless::spsc::Queue<T, N>; /// * `N` - Size of the queue. pub struct MessageQueueStorage<T, const N: usize> { /// Marks whether this storage has been initialized. - _initialized: InternalCell<bool>, + initialized: InternalCell<bool>, /// Buffer for the queue structure. - _queue_buffer: InternalCell<QueueBuffer>, + queue_buffer: InternalCell<QueueBuffer>, /// Buffer for the queue data. - _queue_data: Mutex<QueueData<T, N>>, + queue_data: Mutex<QueueData<T, N>>, } impl<T, const N: usize> MessageQueueStorage<T, N> { /// Creates new storage. pub const fn new() -> Self { MessageQueueStorage { - _initialized: InternalCell::new(false), - _queue_buffer: InternalCell::new(QueueBuffer::new()), - _queue_data: Mutex::new(QueueData::new()), + initialized: InternalCell::new(false), + queue_buffer: InternalCell::new(QueueBuffer::new()), + queue_data: Mutex::new(QueueData::new()), } } + /// Returns initialization status of this storage. + pub fn is_initialized(&'static self) -> bool { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // the `init` function. + unsafe { *self.initialized.as_ref() } + } + /// Creates new handle to a queue allocated in this storage. /// /// Returns `Some(handle)` if this storage has been initialized, `None` otherwise. - pub fn create_queue_handle(&'static self) -> Option<MessageQueueHandle<T>> { - todo!() + pub fn create_handle(&'static self) -> Option<MessageQueueHandle<T, N>> { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // the `init` function. + match unsafe { *self.initialized.as_ref() } { + true => { + // SAFETY: This is safe because storage has been initialized. + let message_queue = unsafe { self.message_queue() }; + Some(MessageQueueHandle::new(message_queue)) + } + false => None, + } + } + + /// Initializes this storage. + /// + /// TODO: Returns + pub(crate) fn init(&'static self) -> Result<(), InitError> { + // SAFETY: This is safe, because it can't be borrowed externally and is only modified in + // this function. + if unsafe { *self.initialized.as_ref() } { + return Err(InitError::StorageAlreadyInitialized); + } + + let queue = MessageQueue::<T, N>::new(&self.queue_data); + + // SAFETY: This is safe, because it is borrowed mutably only here. It can be modified + // (initialized) only once, because it is guarded by the `initialized` field. No external + // borrow can be made before initialization. + unsafe { + // Because the `MessageQueue` structure is of a constant size, the `queue_buffer` field is + // statically allocated with enough memory for a 'placement new'. + let queue_buffer = + self.queue_buffer.as_mut_ref().as_mut_ptr() as *mut MessageQueue<T, N>; + core::ptr::write(queue_buffer, queue); + } + + // SAFETY: This is safe because it is only modified only here, and can't be externally + // borrowed. + unsafe { + *self.initialized.as_mut_ref() = true; + } + + Ok(()) + } + + /// Returns a reference to the stored MessageQueue structer.
```suggestion /// Returns a reference to the stored MessageQueue structure. ```
aerugo
github_2023
others
11
n7space
SteelPh0enix
@@ -29,57 +30,54 @@ unsafe impl Sync for TaskletPtr {} unsafe impl Send for TaskletPtr {} impl TaskletPtr { - /// Creates new pointer + /// Creates new from tasklet referernce
```suggestion /// Creates new tasklet pointer from referernce ```
aerugo
github_2023
others
19
n7space
SteelPh0enix
@@ -0,0 +1,84 @@ +use super::*; + +struct MockDataProvider { + data_ready: bool, +} + +impl MockDataProvider { + const fn new() -> Self { + MockDataProvider { data_ready: false } + } + + fn set_data_ready(&mut self, data_ready: bool) { + self.data_ready = data_ready + } +} + +impl DataProvider<()> for MockDataProvider { + fn data_ready(&self) -> bool { + self.data_ready + } + + fn get_data(&self) -> Option<()> { + if self.data_ready { + Some(()) + } else { + None + } + } +} + +/// @SRS{ROS-FUN-RTOS-50} +/// @SRS{ROS-FUN-RTOS-70} +/// @SRS{ROS-FUN-RTOS-80}
In other projects we usually add comments for tests, explaining what they are testing (Given/When/Then formula). If you're going to use the same tools for requirement generation, maybe you also should add these comments?
aerugo
github_2023
others
21
n7space
SteelPh0enix
@@ -0,0 +1,26 @@ +use assert_cmd::Command; +use test_binary::build_test_binary; + +/// @SRS{ROS-FUN-RTOS-10} +/// @SRS{ROS-FUN-RTOS-90} +/// @SRS{ROS-FUN-RTOS-100} +/// @SRS{ROS-FUN-RTOS-110} +#[cfg_attr(not(doc), test)] +fn req_test_tasklet_priority() { + let test_bin_path = + build_test_binary("test-tasklet-priority", "testbins").expect("error building test binary"); + + Command::new(test_bin_path) + .timeout(std::time::Duration::from_secs(1)) + .assert() + .success() + .code(0) + .stdout( + r#"TaskB: 1 +TaskB: 2 +TaskB: 3 +TaskB: 4 +TaskB: 5 +"#,
remove exit from TaskB and check if TaskC executes after TaskB finishes?
aerugo
github_2023
others
18
n7space
Glamhoth
@@ -72,6 +41,23 @@ impl Watchdog { } } + /// Converts duration to watchdog counter value
Parameter documentation is missing (here and in some other functions in this file)
aerugo
github_2023
others
18
n7space
Glamhoth
@@ -72,6 +41,23 @@ impl Watchdog { } } + /// Converts duration to watchdog counter value + fn convert_duration_to_counter_value(duration: MillisDurationU32) -> u16 {
I'd move free functions at the end of the `impl` block
aerugo
github_2023
others
18
n7space
Glamhoth
@@ -1,50 +1,109 @@ //! System HAL implementation for Cortex-M SAMV71 target. +use aerugo_cortex_m::Mutex; use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; use bare_metal::CriticalSection; -use crate::peripherals::Peripherals; +use crate::drivers::watchdog::config::WatchdogConfig; +use crate::drivers::watchdog::Watchdog; +use crate::error::HalError; +use crate::system_peripherals::SystemPeripherals; +use crate::user_peripherals::UserPeripherals; use internal_cell::InternalCell; +use pac; + +/// This lock will prevent from creating HAL instance twice in the system. +/// Since HAL manages the access to peripherals, creating and using multiple +/// instances of it could be unsafe. +static HAL_CREATION_LOCK: Mutex<bool> = Mutex::new(false); /// HAL implementation for Cortex-M SAMV71. pub struct Hal { /// Hardware peripherals. - peripherals: InternalCell<Option<Peripherals>>, + user_peripherals: Option<UserPeripherals>, + /// System peripherals. + system_peripherals: InternalCell<SystemPeripherals>, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; - /// Create new HAL instance. - pub fn new(peripherals: Peripherals) -> Self { - Hal { - peripherals: InternalCell::new(Some(peripherals)), - } + /// Create new HAL instance from PAC peripherals. + /// SAFETY: This function is safe to call only once.
Docs formatting
aerugo
github_2023
others
18
n7space
Glamhoth
@@ -1,50 +1,109 @@ //! System HAL implementation for Cortex-M SAMV71 target. +use aerugo_cortex_m::Mutex; use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; use bare_metal::CriticalSection; -use crate::peripherals::Peripherals; +use crate::drivers::watchdog::config::WatchdogConfig; +use crate::drivers::watchdog::Watchdog; +use crate::error::HalError; +use crate::system_peripherals::SystemPeripherals; +use crate::user_peripherals::UserPeripherals; use internal_cell::InternalCell; +use pac; + +/// This lock will prevent from creating HAL instance twice in the system. +/// Since HAL manages the access to peripherals, creating and using multiple +/// instances of it could be unsafe. +static HAL_CREATION_LOCK: Mutex<bool> = Mutex::new(false); /// HAL implementation for Cortex-M SAMV71. pub struct Hal { /// Hardware peripherals. - peripherals: InternalCell<Option<Peripherals>>, + user_peripherals: Option<UserPeripherals>, + /// System peripherals. + system_peripherals: InternalCell<SystemPeripherals>, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; - /// Create new HAL instance. - pub fn new(peripherals: Peripherals) -> Self { - Hal { - peripherals: InternalCell::new(Some(peripherals)), - } + /// Create new HAL instance from PAC peripherals. + /// SAFETY: This function is safe to call only once. + /// Subsequent calls will return an error, indicating that HAL instance has already been created. + pub fn new() -> Result<Self, HalError> { + HAL_CREATION_LOCK.lock(|lock| { + if *lock { + return Err(HalError::HalAlreadyCreated); + } + + *lock = true;
Lock should end here
aerugo
github_2023
others
18
n7space
Glamhoth
@@ -0,0 +1,155 @@ +//! Implementation of HAL Watchdog driver. +//! +//! Watchdog can be used to unconditionally reset or interrupt the MCU when program halts. +//! To indicate that program is running, watchdog needs to be "fed" periodically. +//! Minimal frequency of feeding can be adjusted by setting watchdog counter reset value (duration). +//! Behavior of watchdog, it's state, and duration can be set using provided API. +//! +//! # Implementation remarks +//! On SAMV71, Watchdog is enabled by default with duration of 16 seconds, +//! and can only be configured ONCE. Consequent configurations will have no effect, +//! until the MCU performs a hard reset (via reset controller or power cycle). + +pub mod watchdog_config; +pub mod watchdog_error; + +use crate::pac::WDT; +use fugit::MillisDurationU32; +pub use watchdog_config::WatchdogConfig; +pub use watchdog_error::WatchdogError; + +use self::watchdog_config::MAXIMUM_WATCHDOG_DURATION; + +/// Structure representing a watchdog. +pub struct Watchdog { + /// Watchdog instance. + wdt: WDT, + /// Indicates whether the watchdog has already been configured (or disabled). + configured: bool, +} + +/// # Safety +/// Watchdog does not auto-implement Sync due to WDT structure containing a pointer. +/// Since it owns WDT, and it's running in single-core environment, it's safe to share. +unsafe impl Sync for Watchdog {} + +impl Watchdog { + /// Create a watchdog instance from PAC peripheral. + /// + /// # Arguments
`Parameters` to be inline with the rest of the docs
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,12 @@ +[package] +name = "internal-cell" +version = "1.0.0"
I'd keep the version same as the system, so `0.0.1` for now. `env-parser` has `1.0.0` because it's completely separate and most likely won't be changed anymore.
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -4,23 +4,41 @@ use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; use bare_metal::CriticalSection; use crate::peripherals::Peripherals; +use internal_cell::InternalCell; /// HAL implementation for Cortex-M SAMV71. pub struct Hal { /// Hardware peripherals. - _peripherals: Peripherals, + _peripherals: InternalCell<Option<Peripherals>>, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; /// Create new HAL instance. - pub const fn new(peripherals: Peripherals) -> Self { + pub const fn new() -> Self { Hal { - _peripherals: peripherals, + _peripherals: InternalCell::new(None),
Remove `_` as this field is now used.
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -4,23 +4,41 @@ use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; use bare_metal::CriticalSection; use crate::peripherals::Peripherals; +use internal_cell::InternalCell; /// HAL implementation for Cortex-M SAMV71. pub struct Hal { /// Hardware peripherals. - _peripherals: Peripherals, + _peripherals: InternalCell<Option<Peripherals>>, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; /// Create new HAL instance. - pub const fn new(peripherals: Peripherals) -> Self { + pub const fn new() -> Self { Hal { - _peripherals: peripherals, + _peripherals: InternalCell::new(None), } } + + /// Set peripherals instance used by HAL. If peripherals have already been set, it has no effect. + pub fn set_peripherals(&self, peripherals: Peripherals) {
This should panic if peripherals are set twice, as this would clearly be an error, or at least return `Result`.
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -4,23 +4,41 @@ use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; use bare_metal::CriticalSection; use crate::peripherals::Peripherals; +use internal_cell::InternalCell; /// HAL implementation for Cortex-M SAMV71. pub struct Hal { /// Hardware peripherals. - _peripherals: Peripherals, + _peripherals: InternalCell<Option<Peripherals>>, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; /// Create new HAL instance. - pub const fn new(peripherals: Peripherals) -> Self {
Maybe `Hal` should be initialized with `Peripherals`, and then we move responsibility of initializing it at runtime upwards? Maybe `Aerugo` shall use `lazy_init` to initialize Hal at runtime?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -6,10 +6,14 @@ SAMV71 implementation of aerugo HAL. #![warn(clippy::missing_docs_in_private_items)] #![warn(rustdoc::missing_crate_level_docs)] +extern crate internal_cell; + pub(crate) use fugit as time; +pub(crate) use samv71q21_pac as pac; pub mod hal; pub mod peripherals; pub use self::hal::Hal; pub use self::peripherals::Peripherals; +pub use embedded_hal;
Just question: should our HAL do this `pub`?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,120 @@ +//! Implementation of HAL for Watchdog + +use embedded_hal::watchdog::WatchdogDisable; + +use crate::embedded_hal::watchdog; +use crate::pac::WDT; + +/// Structure representing a watchdog +pub struct Watchdog { + /// Watchdog instance + wdt: WDT, + /// Indicates whether the watchdog has been configured (or disabled). + /// + /// Note that watchdog can be configured or disabled only once. + /// Configuration is locked until MCU performs a hard reset. + /// This flag prevents it from being configured twice. + configured: bool, +} + +/// SAFETY: Watchdog does not auto-implement Sync due to WDT structure. +/// Since it owns WDT, and it's running in single-core environment, it's safe to share. +unsafe impl Sync for Watchdog {} + +/// Structure representing Watchdog configuration. +/// +/// Note that watchdog can be configured only once. +/// Configuration is locked until MCU performs a hard reset. +pub struct WatchdogConfiguration {
Move to a different file maybe? `src/peripherals/watchdog/watchdog_config.rs`? \+ We have `Config` in other places instead of `Configuration`
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,41 @@ +//! Access to the hardware peripherals. + +pub mod watchdog; + +use aerugo_cortex_m::Mutex; +use samv71q21_pac::CorePeripherals as cortex_peripherals; +use samv71q21_pac::Peripherals as samv71_peripherals; + +/// Mutex indicating whether the peripherals instance have already been taken. +static PERIPHERALS_TAKEN: Mutex<bool> = Mutex::new(false); + +/// Peripherals structure. +pub struct Peripherals { + /// Raw MCU peripherals + pub mcu_pac: samv71_peripherals, + /// Raw Cortex-M peripherals + pub cortex_pac: cortex_peripherals, +} + +impl Peripherals { + /// Create new peripherals instance. This function can be called successfully only once. + pub fn new() -> Option<Peripherals> { + PERIPHERALS_TAKEN.lock(|peripherals_taken| { + if *peripherals_taken { + return None; + } + + *peripherals_taken = true;
Lock should end here.
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,120 @@ +//! Implementation of HAL for Watchdog + +use embedded_hal::watchdog::WatchdogDisable; + +use crate::embedded_hal::watchdog; +use crate::pac::WDT; + +/// Structure representing a watchdog +pub struct Watchdog { + /// Watchdog instance + wdt: WDT, + /// Indicates whether the watchdog has been configured (or disabled). + /// + /// Note that watchdog can be configured or disabled only once. + /// Configuration is locked until MCU performs a hard reset. + /// This flag prevents it from being configured twice. + configured: bool, +} + +/// SAFETY: Watchdog does not auto-implement Sync due to WDT structure. +/// Since it owns WDT, and it's running in single-core environment, it's safe to share. +unsafe impl Sync for Watchdog {} + +/// Structure representing Watchdog configuration. +/// +/// Note that watchdog can be configured only once. +/// Configuration is locked until MCU performs a hard reset. +pub struct WatchdogConfiguration { + /// If true, watchdog stays enabled. + pub enabled: bool, + /// If true, watchdog will reset the MCU on timeout. + pub reset_enabled: bool, + /// Defines the counter value for watchdog. + pub counter: u16, + /// If true, watchdog will run in idle state. + pub run_in_idle: bool, + /// If true, watchdog will run in debug state. + pub run_in_debug: bool, + /// If true, watchdog underflow or error will trigger interrupt. + pub interrupt_enabled: bool, +} + +impl Default for WatchdogConfiguration { + fn default() -> Self { + WatchdogConfiguration { + enabled: true, + reset_enabled: true, + counter: 0xFFF, + run_in_idle: false, + run_in_debug: false, + interrupt_enabled: false, + } + } +} + +impl Watchdog { + /// Create a watchdog instance + pub const fn new(wdt: WDT) -> Self { + Self { + wdt, + configured: false, + } + } + + /// Set watchdog configuration + /// + /// Note that watchdog can be configured only once. + /// Configuration is locked until MCU performs a hard reset. + pub fn configure(&mut self, configuration: WatchdogConfiguration) {
This should return `Result` with an appriopriate error.
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,120 @@ +//! Implementation of HAL for Watchdog + +use embedded_hal::watchdog::WatchdogDisable; + +use crate::embedded_hal::watchdog; +use crate::pac::WDT; + +/// Structure representing a watchdog +pub struct Watchdog { + /// Watchdog instance + wdt: WDT, + /// Indicates whether the watchdog has been configured (or disabled). + /// + /// Note that watchdog can be configured or disabled only once. + /// Configuration is locked until MCU performs a hard reset. + /// This flag prevents it from being configured twice. + configured: bool, +} + +/// SAFETY: Watchdog does not auto-implement Sync due to WDT structure. +/// Since it owns WDT, and it's running in single-core environment, it's safe to share. +unsafe impl Sync for Watchdog {} + +/// Structure representing Watchdog configuration. +/// +/// Note that watchdog can be configured only once. +/// Configuration is locked until MCU performs a hard reset. +pub struct WatchdogConfiguration { + /// If true, watchdog stays enabled. + pub enabled: bool, + /// If true, watchdog will reset the MCU on timeout. + pub reset_enabled: bool, + /// Defines the counter value for watchdog. + pub counter: u16, + /// If true, watchdog will run in idle state. + pub run_in_idle: bool, + /// If true, watchdog will run in debug state. + pub run_in_debug: bool, + /// If true, watchdog underflow or error will trigger interrupt. + pub interrupt_enabled: bool, +} + +impl Default for WatchdogConfiguration { + fn default() -> Self { + WatchdogConfiguration { + enabled: true, + reset_enabled: true, + counter: 0xFFF, + run_in_idle: false, + run_in_debug: false, + interrupt_enabled: false, + } + } +} + +impl Watchdog { + /// Create a watchdog instance + pub const fn new(wdt: WDT) -> Self { + Self { + wdt, + configured: false, + } + } + + /// Set watchdog configuration + /// + /// Note that watchdog can be configured only once. + /// Configuration is locked until MCU performs a hard reset. + pub fn configure(&mut self, configuration: WatchdogConfiguration) { + if self.configured { + return; + } + + // It's unsafe per SAMV71 documentation to modify configuration and enable/disable + // watchdog at the same time, therefore disabling is handled separately. + if !configuration.enabled { + self.disable(); + return; + } + + let clamped_counter_value = configuration.counter.clamp(0, 2u16.pow(12) - 1); + + // SAFETY: WDV is 12-bit field, value from configuration is clamped to (2^12)-1 + self.wdt.mr.modify(|_, w| unsafe { + w.wdidlehlt() + .variant(!configuration.run_in_idle) + .wddbghlt() + .variant(!configuration.run_in_debug) + .wdd() + .bits(clamped_counter_value) + .wdrsten() + .bit(configuration.reset_enabled) + .wdfien() + .variant(configuration.interrupt_enabled) + .wdv() + .bits(clamped_counter_value) + });
Shouldn't this set `self.configured`?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -15,19 +15,31 @@ static TIME_START: Lazy<SystemTime> = Lazy::new(SystemTime::now); /// HAL implementation for x86. pub struct Hal { /// Hardware peripherals. - _peripherals: Peripherals, + #[allow(dead_code)] + peripherals: Peripherals, } impl Hal { /// Frequency for the time types (TODO) const TIMER_FREQ: u32 = 1_000_000; /// Create new HAL instance. - pub const fn new(peripherals: Peripherals) -> Self { + pub const fn new() -> Self { Hal { - _peripherals: peripherals, + peripherals: Peripherals {}, } } + + /// Set peripherals instance used by HAL + #[allow(unused_variables)] + pub fn set_peripherals(&self, peripherals: Peripherals) { + // This is currently no-op, as x86 does not provide any peripherals. + } + + /// Returns PAC peripherals for the user. Can be called successfully only once. + pub fn peripherals(&self) -> Option<Peripherals> { + Some(Peripherals {})
Shouldn't this use `Peripherals::new`?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -56,11 +56,21 @@ impl Aerugo { /// # Safety /// This shouldn't be called in more that [one place](crate::aerugo::AERUGO). const fn new() -> Self { - let peripherals = Peripherals {}; + Aerugo { hal: Hal::new() } + } - Aerugo { - hal: Hal::new(peripherals), - } + /// Initialize the system runtime. + pub fn initialize(&'static self) { + let peripherals = + Peripherals::new().expect("Cannot initialize peripherals more than once!"); + self.hal.set_peripherals(peripherals); + } + + /// Returns PAC peripherals for the user + pub fn peripherals(&'static self) -> Peripherals {
Return `Option` to the user, so that he can handle it (user may want to do something else than `expect`).
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,137 @@ +//! Implementation of HAL for Watchdog +//! +//! Watchdog can be used to unconditionally reset or interrupt the MCU when program halts. +//! To indicate that program is running, watchdog needs to be "fed" periodically. +//! Minimal frequency of feeding can be adjusted by setting watchdog counter reset value (duration). +//! Behavior of watchdog, it's state and duration can be set using provided API. +//! +//! # Implementation remarks +//! On SAMV71, Watchdog is enabled by default with duration of 16 seconds, +//! and can only be configured ONCE. Consequent configurations will have no effect, +//! until the MCU performs a hard reset (via reset controller or power cycle). + +use crate::pac::WDT; + +/// Possible watchdog errors +#[derive(Debug, Copy, Clone, Eq, PartialEq)] +pub enum WatchdogError { + /// Tried to configure watchdog more than once. + WatchdogAlreadyConfigured, +} + +/// Structure representing Watchdog configuration. +/// +/// Note that watchdog can be configured only once. +/// Subsequent configuration is locked until MCU performs a hard reset. +pub struct WatchdogConfig { + /// If true, watchdog stays enabled. + pub enabled: bool, + /// If true, watchdog will reset the MCU on timeout. + pub reset_enabled: bool, + /// Defines the reset value for watchdog's counter in watchdog clock cycles. + pub duration: u16, + /// If true, watchdog will run in idle state. + pub run_in_idle: bool, + /// If true, watchdog will run in debug state. + pub run_in_debug: bool, + /// If true, watchdog underflow or error will trigger interrupt. + pub interrupt_enabled: bool, +} + +impl Default for WatchdogConfig { + fn default() -> Self { + WatchdogConfig { + enabled: true, + reset_enabled: true, + duration: 0xFFF, + run_in_idle: false, + run_in_debug: false, + interrupt_enabled: false, + } + } +} + +/// Structure representing a watchdog +pub struct Watchdog { + /// Watchdog instance + wdt: WDT, + /// Indicates whether the watchdog has already been configured (or disabled). + configured: bool, +} + +/// SAFETY: Watchdog does not auto-implement Sync due to WDT structure. +/// Since it owns WDT, and it's running in single-core environment, it's safe to share. +unsafe impl Sync for Watchdog {} + +impl Watchdog { + /// Create a watchdog instance + pub const fn new(wdt: WDT) -> Self { + Self { + wdt, + configured: false, + } + } + + /// Set watchdog configuration + /// + /// Note that watchdog can be configured only once. + /// Configuration is locked until MCU performs a hard reset. + pub fn configure(&mut self, configuration: WatchdogConfig) -> Result<(), WatchdogError> { + if self.configured { + return Err(WatchdogError::WatchdogAlreadyConfigured); + } + + // It's unsafe per SAMV71 documentation to modify configuration and enable/disable + // watchdog at the same time, therefore disabling is handled separately. + if !configuration.enabled { + self.disable()?; + return Ok(()); + } + + let clamped_counter_value = configuration.duration.clamp(0, 2u16.pow(12) - 1); + + // SAFETY: WDV is 12-bit field, value from configuration is clamped to (2^12)-1 + self.wdt.mr.modify(|_, w| unsafe { + w.wdidlehlt() + .variant(!configuration.run_in_idle) + .wddbghlt() + .variant(!configuration.run_in_debug) + .wdd() + .bits(clamped_counter_value) + .wdrsten() + .bit(configuration.reset_enabled) + .wdfien() + .variant(configuration.interrupt_enabled) + .wdv() + .bits(clamped_counter_value) + }); + + self.configured = true; + Ok(()) + } + + /// Returns true if watchdog has been already configured, false otherwise. + pub fn has_been_configured(&self) -> bool {
`was_configured`?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -0,0 +1,102 @@ +#![no_std] +#![no_main] + +extern crate cortex_m; +extern crate cortex_m_rt as rt; +extern crate panic_semihosting; + +use aerugo::hal::peripherals::watchdog::{Watchdog, WatchdogConfig}; +use aerugo::{ + InitApi, MessageQueueHandle, MessageQueueStorage, TaskletConfig, TaskletStorage, AERUGO, +}; +use cortex_m_semihosting::hprintln; +use rt::entry; + +struct WdtTaskContext { + watchdog: Watchdog, + counter: u32, + queue_handle: MessageQueueHandle<u32, 10>, +} + +fn watchdog_task(_counter: u32, context: &mut WdtTaskContext) { + context.watchdog.feed(); + context.counter = context.counter.wrapping_add(1); + + context + .queue_handle + .send_data(context.counter) + .expect("Unable to send data from task."); +} + +static WATCHDOG_TASK_STORAGE: TaskletStorage<u32, WdtTaskContext> = TaskletStorage::new(); +static DATA_QUEUE: MessageQueueStorage<u32, 10> = MessageQueueStorage::new();
Rewrite this example to use cyclic tasklet
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -56,10 +58,30 @@ impl Aerugo { /// # Safety /// This shouldn't be called in more that [one place](crate::aerugo::AERUGO). const fn new() -> Self { - let peripherals = Peripherals {}; - Aerugo { - hal: Hal::new(peripherals), + hal: InternalCell::new(None), + } + } + + /// Initialize the system runtime. + pub fn initialize(&'static self) {
Return `Result`
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -346,7 +368,15 @@ impl RuntimeApi for Aerugo { type Duration = crate::time::TimerDurationU64<1_000_000>; fn get_system_time(&'static self) -> Self::Instant { - self.hal.get_system_time() + // SAFETY: This is safe, because it's a single-core environment, + // and no other references to Hal should exist during this call. + unsafe { + self.hal + .as_ref() + .as_ref()
Double `as_ref`?
aerugo
github_2023
others
16
n7space
Glamhoth
@@ -28,6 +28,10 @@ pub enum RuntimeError { ExecutorTaskletQueueFull, /// Enqueued data to a full data queue. DataQueueFull, + /// Tried to perform an operation before system initialization. + SystemNotInitialized, + /// Tried to initialize system more than once + SystemReinitialized,
`SystemAlreadyInitialized` to be in line with `StorageAlreadyInitialized`?
aerugo
github_2023
others
17
n7space
SteelPh0enix
@@ -328,12 +334,62 @@ impl InitApi for Aerugo { todo!() } - fn subscribe_tasklet_to_cyclic<T, C>( + /// Subscribes tasklet to the cyclic execution. + /// + /// Tasklet subscribes for cyclic execution. Tasklet will be executed in specified period, + /// or will be always ready for execution if such period was not specified. On execution + /// tasklet won't receive any data, so cycling tasklets are useful mostly as ex. producers or + /// some periodic housekeeping operations. + /// + /// Each tasklet can be subscribed to at maximum on data provider. + /// + /// # Generic Arguments + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `tasklet` - Handle to the target tasklet. + /// * `period` - Time period of the execution. + /// + /// # Return + /// `()` if successful, `Self::Error` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because subscription is safe + /// only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// # + /// # fn task(_: (), _: &mut ()) {} + /// # + /// # static TASK_STORAGE: TaskletStorage<(), ()> = TaskletStorage::new(); + /// # + /// fn main() { + /// # let task_config = TaskletConfig::default(); + /// # AERUGO + /// # .create_tasklet(TaskletConfig::default(), task, &TASK_STORAGE) + /// # .expect("Unable to create Tasklet"); + /// let task_handle = TASK_STORAGE.create_handle().expect("Failed to create Task handle"); + /// + /// AERUGO + /// .subscribe_tasklet_to_cyclic(&task_handle, None) + /// .expect("Failed to subscribe Task to cyclic execution"); + /// } + /// ``` + fn subscribe_tasklet_to_cyclic<C>( &'static self, - _tasklet: &TaskletHandle<T, C>, - _period: Self::Duration, + tasklet_handle: &TaskletHandle<(), C>, + period: Option<Self::Duration>, ) -> Result<(), Self::Error> { - todo!() + let tasklet = tasklet_handle.tasklet(); + + unsafe {
safety comment?
aerugo
github_2023
others
17
n7space
SteelPh0enix
@@ -0,0 +1,68 @@ +//! System time manager. +//! +//! This module contains a system time manager. It's responsibility is to keep track of tasklets +//! and events that are based on time. + +mod cyclic_execution; + +use self::cyclic_execution::CyclicExecution; + +use heapless::Vec; + +use crate::aerugo::{Aerugo, InitError}; +use crate::internal_cell::InternalCell; +use crate::tasklet::TaskletPtr; +use crate::time::MillisDurationU32; + +type CyclicExecutions = Vec<CyclicExecution, { Aerugo::TASKLET_COUNT }>; + +/// System time manager. +/// +/// This shouldn't be created by hand by the user or anywhere else in the code. +/// It should be used as a singleton (crate::aerugo::TIME_MANAGER) and shouldn't be directly accessed +/// by any other part of the system. +pub(crate) struct TimeManager { + cyclic_executions: InternalCell<CyclicExecutions>, +} + +impl TimeManager { + /// Creates new time manager instance. + /// + /// # Safety + /// This shoudln't be called in more than one place.
```suggestion /// This shoudln't be called more than once. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -55,30 +77,157 @@ impl Aerugo { impl InitApi for Aerugo { type Duration = crate::time::MillisDurationU32; + /// Creates new tasklet in the system. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life.
```suggestion /// tasklet for the whole duration of system's life. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -55,30 +77,157 @@ impl Aerugo { impl InitApi for Aerugo { type Duration = crate::time::MillisDurationU32; + /// Creates new tasklet in the system. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `()` is successful, `InitError` otherwise.
```suggestion /// `()` if successful, `InitError` otherwise. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -55,30 +77,157 @@ impl Aerugo { impl InitApi for Aerugo { type Duration = crate::time::MillisDurationU32; + /// Creates new tasklet in the system. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `()` is successful, `InitError` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// #[derive(Default)] + /// struct TaskCtx; + /// + /// fn task(_: u8, _: &mut TaskCtx) {} + /// + /// static TASK_STORAGE: TaskletStorage<u8, TaskCtx> = TaskletStorage::new(); + /// + /// fn main() { + /// let task_config = TaskletConfig::default(); + /// AERUGO.create_tasklet(task_config, task, &TASK_STORAGE).expect("Unable to create Tasklet"); + /// # + /// # assert!(TASK_STORAGE.is_initialized()); + /// + /// // Do something with the tasklet via handle. + /// let task_handle = TASK_STORAGE.create_handle(); + /// # + /// # assert!(task_handle.is_some()) + /// } + /// ``` fn create_tasklet<T, C: Default>( &'static self, config: Self::TaskConfig, step_fn: StepFn<T, C>, storage: &'static TaskletStorage<T, C>, ) -> Result<(), Self::Error> { - storage.init(config, step_fn, C::default()) + // SAFETY: This is safe, because this function can be called only during system initialization.
```suggestion // SAFETY: This is safe, as long as this function is called only during system initialization. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -55,30 +77,157 @@ impl Aerugo { impl InitApi for Aerugo { type Duration = crate::time::MillisDurationU32; + /// Creates new tasklet in the system. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `()` is successful, `InitError` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// #[derive(Default)] + /// struct TaskCtx; + /// + /// fn task(_: u8, _: &mut TaskCtx) {} + /// + /// static TASK_STORAGE: TaskletStorage<u8, TaskCtx> = TaskletStorage::new(); + /// + /// fn main() { + /// let task_config = TaskletConfig::default(); + /// AERUGO.create_tasklet(task_config, task, &TASK_STORAGE).expect("Unable to create Tasklet"); + /// # + /// # assert!(TASK_STORAGE.is_initialized()); + /// + /// // Do something with the tasklet via handle. + /// let task_handle = TASK_STORAGE.create_handle(); + /// # + /// # assert!(task_handle.is_some()) + /// } + /// ``` fn create_tasklet<T, C: Default>( &'static self, config: Self::TaskConfig, step_fn: StepFn<T, C>, storage: &'static TaskletStorage<T, C>, ) -> Result<(), Self::Error> { - storage.init(config, step_fn, C::default()) + // SAFETY: This is safe, because this function can be called only during system initialization. + unsafe { storage.init(config, step_fn, C::default()) } } + /// Creates new tasklet in the system with initialized context data. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `context` - Tasklet context data. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `Error` in case of an error, `Ok(())` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// struct TaskCtx { + /// value: u8, + /// } + /// + /// fn task(_: u8, _: &mut TaskCtx) {} + /// + /// static TASK_STORAGE: TaskletStorage<u8, TaskCtx> = TaskletStorage::new(); + /// + /// fn main() { + /// let task_config = TaskletConfig::default(); + /// let task_context = TaskCtx { value: 42 }; + /// AERUGO.create_tasklet_with_context(task_config, task, task_context, &TASK_STORAGE); + /// # + /// # assert!(TASK_STORAGE.is_initialized()); + /// + /// // Do something with the tasklet via handle. + /// let task_handle = TASK_STORAGE.create_handle(); + /// # + /// # assert!(task_handle.is_some()) + /// } + /// ``` fn create_tasklet_with_context<T, C>( &'static self, config: Self::TaskConfig, step_fn: StepFn<T, C>, context: C, storage: &'static TaskletStorage<T, C>, ) -> Result<(), Self::Error> { - storage.init(config, step_fn, context) + // SAFETY: This is safe, because this function is called only during system initialization.
```suggestion // SAFETY: This is safe as long as this function is called only during system initialization. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -55,30 +77,157 @@ impl Aerugo { impl InitApi for Aerugo { type Duration = crate::time::MillisDurationU32; + /// Creates new tasklet in the system. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `()` is successful, `InitError` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// #[derive(Default)] + /// struct TaskCtx; + /// + /// fn task(_: u8, _: &mut TaskCtx) {} + /// + /// static TASK_STORAGE: TaskletStorage<u8, TaskCtx> = TaskletStorage::new(); + /// + /// fn main() { + /// let task_config = TaskletConfig::default(); + /// AERUGO.create_tasklet(task_config, task, &TASK_STORAGE).expect("Unable to create Tasklet"); + /// # + /// # assert!(TASK_STORAGE.is_initialized()); + /// + /// // Do something with the tasklet via handle. + /// let task_handle = TASK_STORAGE.create_handle(); + /// # + /// # assert!(task_handle.is_some()) + /// } + /// ``` fn create_tasklet<T, C: Default>( &'static self, config: Self::TaskConfig, step_fn: StepFn<T, C>, storage: &'static TaskletStorage<T, C>, ) -> Result<(), Self::Error> { - storage.init(config, step_fn, C::default()) + // SAFETY: This is safe, because this function can be called only during system initialization. + unsafe { storage.init(config, step_fn, C::default()) } } + /// Creates new tasklet in the system with initialized context data. + /// + /// Tasklet is created in the passed `storage` memory. Storage has to be static to keep the stored + /// tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data processed by the tasklet. + /// * `C` - Type of the structure with tasklet context data. + /// + /// # Arguments + /// * `config` - Tasklet creation configuration. + /// * `step_fn` - Tasklet step function. + /// * `context` - Tasklet context data. + /// * `storage` - Static memory storage where the tasklet should be allocated. + /// + /// # Return + /// `Error` in case of an error, `Ok(())` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, TaskletConfig, TaskletStorage, AERUGO}; + /// struct TaskCtx { + /// value: u8, + /// } + /// + /// fn task(_: u8, _: &mut TaskCtx) {} + /// + /// static TASK_STORAGE: TaskletStorage<u8, TaskCtx> = TaskletStorage::new(); + /// + /// fn main() { + /// let task_config = TaskletConfig::default(); + /// let task_context = TaskCtx { value: 42 }; + /// AERUGO.create_tasklet_with_context(task_config, task, task_context, &TASK_STORAGE); + /// # + /// # assert!(TASK_STORAGE.is_initialized()); + /// + /// // Do something with the tasklet via handle. + /// let task_handle = TASK_STORAGE.create_handle(); + /// # + /// # assert!(task_handle.is_some()) + /// } + /// ``` fn create_tasklet_with_context<T, C>( &'static self, config: Self::TaskConfig, step_fn: StepFn<T, C>, context: C, storage: &'static TaskletStorage<T, C>, ) -> Result<(), Self::Error> { - storage.init(config, step_fn, context) + // SAFETY: This is safe, because this function is called only during system initialization. + unsafe { storage.init(config, step_fn, context) } } + /// Creates new message queue in the system. + /// + /// Queue is created in the passed `storage` memory. Storage has to be static to keep the + /// stored tasklet for the whole duration of system life. + /// + /// # Generic Arguments + /// * `T` - Type of the data stored in the queue. + /// * `N` - Size of the queue. + /// + /// # Arguments + /// * `storage` - Static memory storage where the queue should be allocated. + /// + /// # Return + /// `Error` in case of an error, `Ok(())` otherwise. + /// + /// # Safety + /// This function shouldn't be called after the system was started, because it initializes the + /// passed storage which is safe only before that. + /// + /// # Example + /// ``` + /// # use aerugo::{InitApi, MessageQueueStorage, AERUGO}; + /// static QUEUE_STORAGE: MessageQueueStorage<u8, 10> = MessageQueueStorage::new(); + /// + /// fn main() { + /// AERUGO.create_message_queue(&QUEUE_STORAGE); + /// # + /// # assert!(QUEUE_STORAGE.is_initialized()); + /// + /// // Do something with the queue via handle. + /// let queue_handle = QUEUE_STORAGE.create_handle(); + /// # + /// # assert!(queue_handle.is_some()) + /// } + /// ``` fn create_message_queue<T, const N: usize>( &'static self, storage: &'static MessageQueueStorage<T, N>, ) -> Result<(), Self::Error> { - storage.init() + // SAFETY: This is safe, because this function can be called only during system initialization.
```suggestion // SAFETY: This is safe as long as this function is called only during system initialization. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -100,8 +303,11 @@ impl InitApi for Aerugo { let tasklet = tasklet_handle.tasklet(); let queue = queue_handle.queue(); - tasklet.subscribe(queue)?; - queue.register_tasklet(tasklet.ptr())?; + // SAFETY: This is safe, because this function can be called only during system initialization.
```suggestion // SAFETY: This is safe as long as this function is called only during system initialization. ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -1,19 +1,26 @@ //! Trait with data provider functionality. //! -//! Data provider is a structure that provided some kind of data to the -//! [data receiver](crate::data_receiver::DataReceiver). +//! This module contains a trait for a data provider. In the system data providers are structures +//! that stores data that can be then passed to a data receiver (currently only
```suggestion //! This module contains a trait for a data provider. In the system, data providers are structures //! that store the data that can be then passed to a data receiver (currently only ```
aerugo
github_2023
others
14
n7space
SteelPh0enix
@@ -6,22 +6,27 @@ use crate::tasklet::TaskletPtr; /// Trait for generic queue that stores data of type `T`. /// +/// # Generic Parameters /// * `T` - Type of the stored data. pub(crate) trait Queue<T>: DataProvider<T> { /// Registers task to this queue. /// + /// # Parameters /// * `task` - Task to register. /// - /// Returns `InitError` in case of an error, `Ok(())` otherwise. - fn register_tasklet(&self, tasklet: TaskletPtr) -> Result<(), InitError>; + /// # Returns + /// `()` if successful, `InitError` otherwise. + unsafe fn register_tasklet(&self, tasklet: TaskletPtr) -> Result<(), InitError>;
safety comment?
aerugo
github_2023
others
12
n7space
Glamhoth
@@ -0,0 +1,11 @@ +#!/bin/bash + +aerugo_x86() { + cargo clippy -p aerugo -F use-aerugo-x86 -- -D warnings
add `--tests` too maybe?
aerugo
github_2023
others
9
n7space
SteelPh0enix
@@ -1,29 +1,32 @@ #![no_std] #![no_main] -#![allow(non_upper_case_globals)] extern crate panic_semihosting; use cortex_m::peripheral::syst::SystClkSource; use cortex_m_rt::{entry, exception}; -use aerugo::{AERUGO, InitApi, MessageQueueStorage, TaskletConfig, TaskletStorage}; +use aerugo::{InitApi, MessageQueueStorage, TaskletConfig, TaskletStorage, AERUGO}; #[allow(dead_code)] struct TaskAData { a: u8, b: u32, } +fn task_a(_: u8) {} + #[allow(dead_code)] struct TaskBData { a: u16, b: u16, } -static tasklet_a: TaskletStorage<u8, TaskAData> = TaskletStorage::new(); -static tasklet_b: TaskletStorage<u8, TaskBData> = TaskletStorage::new(); -static queue_x: MessageQueueStorage<u8, 16> = MessageQueueStorage::new(); +fn task_b(_: u8) {} + +static TASK_A: TaskletStorage<u8, TaskAData> = TaskletStorage::new();
I don't like the fact that storage has exactly the same name as function - add `_STORAGE` suffix?
aerugo
github_2023
others
7
n7space
SteelPh0enix
@@ -1,2 +1,70 @@ # aerugo -Safety-critical applications oriented Real-Time Operating System written in Rust +Safety-critical applications oriented Real-Time Operating System written in Rust. + +This project is developed as part of the European Space Agency activity +[Evaluation of Rust Usage in Space Applications by Developing BSP and RTOS Targeting SAMV71](https://activities.esa.int/4000140241) + +## Features + +`aerugo` targets ATSAMV71Q21 microcontroller based on the 32-bit ARM Cortex-M7 processor. It's design is +inspired by purely functional programming paradigm and transputers architecture. + +* RTOS is implemented in a form of an executor instead of classic scheduler and doesn't support preemption. +* Executor runs tasklets, which are fine-grained units of computation, that execute a processing step in a +finite amount of time. + +## Project structure + +The repository structure is as follows: + +- `aerugo-hal` - Traits for HAL used in the system. +- `arch` - Code specific for given architecture. +- `examples` - Examples of system usage. +- `scripts` - Handy scripts for automating some of the work. +- `src` - Code of the core system. +- `utils` - Code of additional utils. + +## Cloning + +## Building + +aerugo requires nightly, make sure you have it installed: \ +`rustup toolchain install nightly` + +For the Cortex-M7 platform you first need to install that target via `rustup`: \ +`rustup target add thumbv7em-none-eabihf` + +Then to build the system run: \ +`cargo build -p aerugo --features=use-aerugo-cortex-m --target=thumbv7em-none-eabihf` + +x86 target is also supported for development purposes: \ +`cargo build -p aerugo --features=use-aerugo-x86 --target=x86_64-unknown-linux-gnu` + +## Tests + +Tests can be build and run using a bash script. For all tests run: \ +`./scripts/run_tests.sh` + +or for specific package run for example: \ +`./scripts/run_tests.sh aerugo_x86` + +Tests can also be run using `cargo tests`.
```suggestion Tests can also be run using `cargo test` with `--features` and `--target` flags. ```
aerugo
github_2023
others
6
n7space
SteelPh0enix
@@ -6,6 +6,8 @@ Cortex-M specific implementation for Aerugo. #![warn(clippy::missing_docs_in_private_items)] #![warn(rustdoc::missing_crate_level_docs)] -pub mod mutex; +mod logger; +mod mutex; +pub use self::logger::logln;
I don't like `logln` name, why not just `log`? Assumed behavior is usually that it adds a full entry (line of text in this case i guess?) to log, no need the "line" suffix there
aerugo
github_2023
others
6
n7space
SteelPh0enix
@@ -0,0 +1,109 @@ +//! System scheduler. + +use heapless::binary_heap::{BinaryHeap, Max}; + +use crate::aerugo::{error::RuntimeError, Aerugo}; +use crate::api::RuntimeApi; +use crate::arch::Mutex; +use crate::task::TaskStatus; +use crate::tasklet::TaskletPtr; + +/// Type for the tasklet execution queue +type TaskletQueue<const N: usize> = BinaryHeap<TaskletPtr, Max, N>; + +/// System scheduler. +pub(crate) struct Executor { + /// Tasklet queue. + tasklet_queue: Mutex<TaskletQueue<8>>,
That `8` should probably be tailorable somehow, somewhere from the user code/config...
aerugo
github_2023
others
6
n7space
SteelPh0enix
@@ -0,0 +1,109 @@ +//! System scheduler. + +use heapless::binary_heap::{BinaryHeap, Max}; + +use crate::aerugo::{error::RuntimeError, Aerugo}; +use crate::api::RuntimeApi; +use crate::arch::Mutex; +use crate::task::TaskStatus; +use crate::tasklet::TaskletPtr; + +/// Type for the tasklet execution queue +type TaskletQueue<const N: usize> = BinaryHeap<TaskletPtr, Max, N>; + +/// System scheduler. +pub(crate) struct Executor { + /// Tasklet queue. + tasklet_queue: Mutex<TaskletQueue<8>>, + /// System API. + system_api: &'static Aerugo, +} + +impl Executor { + /// Creates new executor instance. + /// + /// * `system_api` - System API. + pub(crate) const fn new(system_api: &'static Aerugo) -> Self { + Executor { + tasklet_queue: Mutex::new(BinaryHeap::new()), + system_api, + } + } + + /// Starts tasklet scheduling. + pub(crate) fn run_scheduler(&self) -> ! { + loop { + self.execute_next_tasklet() + .expect("Failure in tasklet execution"); + } + } + + /// Schedules given task for execution. + /// + /// If given task is not already waiting for execution it is put to the execution queue. + /// + /// * `tasklet` - Tasklet to schedule. + /// + /// Returns `RuntimeError` in case of an error, `Ok(())` otherwise. + pub(crate) fn schedule_tasklet(&self, tasklet: TaskletPtr) -> Result<(), RuntimeError> { + let tasklet_status = tasklet.get_status(); + + if tasklet_status == TaskStatus::Sleeping { + self.add_tasklet_to_queue(tasklet)?; + } + + Ok(()) + } + + /// Executes the next tasklet from the queue. + /// + /// Returns `RuntimeError` in case of an error, `Ok(bool)` otherwise indicating if tasklet + /// executed. + fn execute_next_tasklet(&self) -> Result<bool, RuntimeError> { + if let Some(tasklet) = self.get_tasklet_for_execution() { + tasklet.execute(); + tasklet.set_last_execution_time(self.system_api.get_system_time());
maybe split that into execution start and finish time? Or can we measuring this time some other way?
aerugo
github_2023
others
6
n7space
SteelPh0enix
@@ -0,0 +1,68 @@ +//! Handle to a tasklet. +//! +//! Tasklet handle is available to the user of the system to reference and interact with the +//! tasklet via handle interface. All system API functions shall use handles when a reference to +//! tasklet is required, for example in subscribing tasklet to some data source. + +use core::marker::PhantomData; + +use crate::tasklet::TaskletPtr; + +/// Tasklet handle. +/// +/// * `T` - Type that is processed by the tasklet. +/// * `C` - Type of tasklet context data. +pub struct TaskletHandle<T: 'static, C> { + /// Pointer to the tasklet. + tasklet: TaskletPtr, + /// Marker for the type that is processed by the tasklet. + _data_marker: PhantomData<T>, + /// Marker for the type of tasklet context data. + _context_marker: PhantomData<C>, +} + +impl<T: 'static, C> TaskletHandle<T, C> { + /// Creates new tasklet handle. + /// + /// * `tasklet` - Pointer to the tasklet. + pub(crate) fn new(tasklet: TaskletPtr) -> Self { + TaskletHandle { + tasklet, + _data_marker: PhantomData, + _context_marker: PhantomData, + } + } + + /// Returns name of this tasklet. + pub fn get_name(&self) -> &'static str { + self.tasklet.get_name() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task::Task; + use crate::tasklet::{Tasklet, TaskletConfig}; + + fn create_tasklet() -> Tasklet<u8, ()> { + let tasklet_config = TaskletConfig { name: "TaskName" }; + + Tasklet::<u8, ()>::new(tasklet_config) + } + + fn create_tasklet_ptr(tasklet: &Tasklet<u8, ()>) -> TaskletPtr { + let ptr = tasklet as *const Tasklet<u8, ()> as *const ();
replace double-cast with single cast
aerugo
github_2023
others
6
n7space
SteelPh0enix
@@ -0,0 +1,178 @@ +//! Raw tasklet pointer. +//! +//! To hide generic parameters of the `Tasklet` we use `Task` trait. It's necessary for in example +//! storing tasklets that are ready for execution. But then using trait objects creates a dynamic +//! dispatching, which is unwanted in the embedded environment especially in tight loops (like +//! tasklet exectution loop). Additionally we don't need polymorphism, as the trait is not used for +//! defining a shared behavior between different types and only one structure (`Tasklet`) is +//! implementing the trait. +//! +//! This structure is used instead of trait objects (`&'static dyn Task`) and uses a hand-made +//! virtual table. It is based on the fact that `Task` is only implemented for the `Tasklet` so +//! we can safely store `&'static Tasklet<T, C>` in `*const ()`. + +use core::cmp::Ordering; + +use crate::task::TaskStatus; +use crate::tasklet::{tasklet_vtable, TaskletVTable}; +use crate::time::TimerInstantU64; + +/// Raw tasklet pointer. +pub(crate) struct TaskletPtr { + /// Pointer to the `Tasklet<T, C>` structure. + ptr: *const (), + /// Tasklet virtual table. + vtable: &'static TaskletVTable, +} + +unsafe impl Sync for TaskletPtr {} +unsafe impl Send for TaskletPtr {} + +impl TaskletPtr { + /// Creates new pointer + /// + /// * `ptr` - Pointer to memory where tasklet is allocated. + pub(crate) fn new<T: 'static, C>(ptr: *const ()) -> Self { + TaskletPtr { + ptr, + vtable: tasklet_vtable::<T, C>(), + } + } + + /// Returns tasklet name. + #[inline(always)] + pub(crate) fn get_name(&self) -> &'static str { + (self.vtable.get_name)(self.ptr) + } + + /// Returns tasklet status. + #[inline(always)] + pub(crate) fn get_status(&self) -> TaskStatus { + (self.vtable.get_status)(self.ptr) + } + + /// Sets tasklet status. + /// + /// * `status` - New tasklet status. + #[inline(always)] + pub(crate) fn set_status(&self, status: TaskStatus) { + (self.vtable.set_status)(self.ptr, status) + } + + /// Returns last execution time. + #[inline(always)] + pub(crate) fn get_last_execution_time(&self) -> TimerInstantU64<1_000_000> { + (self.vtable.get_last_execution_time)(self.ptr) + } + + /// Sets last execution time. + /// + /// * `time` - Last execution time. + #[inline(always)] + pub(crate) fn set_last_execution_time(&self, time: TimerInstantU64<1_000_000>) { + (self.vtable.set_last_execution_time)(self.ptr, time) + } + + /// Checks if there are any more data for the tasklet to process. + #[inline(always)] + pub(crate) fn has_work(&self) -> bool { + (self.vtable.has_work)(self.ptr) + } + + /// Executes task. + #[inline(always)] + pub(crate) fn execute(&self) { + (self.vtable.execute)(self.ptr) + } +} + +impl Ord for TaskletPtr { + fn cmp(&self, other: &Self) -> Ordering { + self.get_last_execution_time() + .cmp(&other.get_last_execution_time()) + .reverse() + } +} + +impl PartialOrd for TaskletPtr { + fn partial_cmp(&self, other: &Self) -> Option<Ordering> { + self.get_last_execution_time() + .partial_cmp(&other.get_last_execution_time()) + .map(|ordering| ordering.reverse()) + } +} + +impl Eq for TaskletPtr {} + +impl PartialEq for TaskletPtr { + fn eq(&self, other: &Self) -> bool { + self.get_last_execution_time() + .eq(&other.get_last_execution_time()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::task::Task; + use crate::tasklet::{Tasklet, TaskletConfig}; + + fn create_tasklet() -> Tasklet<u8, ()> { + let tasklet_config = TaskletConfig { name: "TaskName" }; + + Tasklet::<u8, ()>::new(tasklet_config) + } + + fn create_tasklet_ptr(tasklet: &Tasklet<u8, ()>) -> TaskletPtr { + let ptr = tasklet as *const Tasklet<u8, ()> as *const ();
fix double-cast
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,57 @@ +//! System HAL. + +mod config; + +pub use self::config::SystemHardwareConfig; + +use bare_metal::CriticalSection; +use core::ops::{Add, Sub}; + +/// System HAL trait. +pub trait SystemHal { + /// Type for an instant in time. + type Instant: Ord + + Copy + + Add<Self::Duration, Output = Self::Instant> + + Sub<Self::Duration, Output = Self::Instant> + + Sub<Self::Instant, Output = Self::Duration>;
Why no `Add<Self::Instant, Output = Self::Duration>`? Is it automatically generated somehow?
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,57 @@ +//! System HAL. + +mod config; + +pub use self::config::SystemHardwareConfig; + +use bare_metal::CriticalSection; +use core::ops::{Add, Sub}; + +/// System HAL trait. +pub trait SystemHal { + /// Type for an instant in time. + type Instant: Ord + + Copy + + Add<Self::Duration, Output = Self::Instant> + + Sub<Self::Duration, Output = Self::Instant> + + Sub<Self::Instant, Output = Self::Duration>; + + /// Type for a duration of time. + type Duration; + + /// Configure system hardware. + /// + /// Implementation should initialize and configure all core system peripherals. + /// + /// * `config` - System hardware configuration. + fn configure_hardware(&mut self, config: SystemHardwareConfig); + + /// Gets current system time timestamp. + fn get_system_time(&self) -> Self::Instant; + + /// Feeds the system watchdog. + fn feed_watchdog(&mut self); + + /// Enters critical section + fn enter_critical() + where + Self: Sized;
kill if not needed
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,57 @@ +//! System HAL. + +mod config; + +pub use self::config::SystemHardwareConfig; + +use bare_metal::CriticalSection; +use core::ops::{Add, Sub}; + +/// System HAL trait. +pub trait SystemHal { + /// Type for an instant in time. + type Instant: Ord + + Copy + + Add<Self::Duration, Output = Self::Instant> + + Sub<Self::Duration, Output = Self::Instant> + + Sub<Self::Instant, Output = Self::Duration>; + + /// Type for a duration of time. + type Duration; + + /// Configure system hardware. + /// + /// Implementation should initialize and configure all core system peripherals. + /// + /// * `config` - System hardware configuration. + fn configure_hardware(&mut self, config: SystemHardwareConfig); + + /// Gets current system time timestamp. + fn get_system_time(&self) -> Self::Instant; + + /// Feeds the system watchdog. + fn feed_watchdog(&mut self); + + /// Enters critical section + fn enter_critical() + where + Self: Sized; + + /// Exits critical section + fn exit_critical() + where + Self: Sized;
kill if not needed
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,57 @@ +//! System HAL. + +mod config; + +pub use self::config::SystemHardwareConfig; + +use bare_metal::CriticalSection; +use core::ops::{Add, Sub}; + +/// System HAL trait. +pub trait SystemHal { + /// Type for an instant in time. + type Instant: Ord + + Copy + + Add<Self::Duration, Output = Self::Instant> + + Sub<Self::Duration, Output = Self::Instant> + + Sub<Self::Instant, Output = Self::Duration>; + + /// Type for a duration of time. + type Duration; + + /// Configure system hardware. + /// + /// Implementation should initialize and configure all core system peripherals. + /// + /// * `config` - System hardware configuration. + fn configure_hardware(&mut self, config: SystemHardwareConfig); + + /// Gets current system time timestamp. + fn get_system_time(&self) -> Self::Instant; + + /// Feeds the system watchdog. + fn feed_watchdog(&mut self); + + /// Enters critical section + fn enter_critical() + where + Self: Sized; + + /// Exits critical section + fn exit_critical() + where + Self: Sized; + + /// Executes closure `f` in an interrupt-free context. + /// + /// * `F` - Closure type. + /// * `R` - Closure return type. + /// + /// * `f` - Closure to execute. + /// + /// Returns closure result. + fn execute_critical<F, R>(f: F) -> R + where + F: FnOnce(&CriticalSection) -> R, + Self: Sized;
kill if not needed
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,60 @@ +//! System HAL implementation for x86 target. + +use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; +use bare_metal::CriticalSection; + +use crate::peripherals::Peripherals; + +/// HAL implementation for x86. +pub struct Hal { + /// Hardware peripherals. + _peripherals: Peripherals, +} + +impl Hal { + /// Create new HAL instance. + pub const fn new(peripherals: Peripherals) -> Self { + Hal { + _peripherals: peripherals, + } + } +} + +impl SystemHal for Hal { + type Instant = crate::time::TimerInstantU64<1_000_000>; + type Duration = crate::time::TimerDurationU64<1_000_000>;
move magic number to named constant (if it's related to system clock or configuration, it should later be made tailorable via config or something like that)
aerugo
github_2023
others
4
n7space
SteelPh0enix
@@ -0,0 +1,75 @@ +//! System HAL implementation for x86 target. + +use std::convert::TryInto; +use std::time::SystemTime; + +use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; +use bare_metal::CriticalSection; +use once_cell::sync::Lazy; + +use crate::peripherals::Peripherals; + +/// Time when system was started +static TIME_START: Lazy<SystemTime> = Lazy::new(SystemTime::now); + +/// HAL implementation for x86. +pub struct Hal { + /// Hardware peripherals. + _peripherals: Peripherals, +} + +impl Hal { + /// Create new HAL instance. + pub const fn new(peripherals: Peripherals) -> Self { + Hal { + _peripherals: peripherals, + } + } +} + +impl SystemHal for Hal { + type Instant = crate::time::TimerInstantU64<1_000_000>; + type Duration = crate::time::TimerDurationU64<1_000_000>;
same as in V71 HAL
aerugo
github_2023
others
4
n7space
Lurkerpas
@@ -0,0 +1,56 @@ +//! System HAL implementation for x86 target. + +use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; +use bare_metal::CriticalSection; + +use crate::peripherals::Peripherals; + +/// HAL implementation for x86.
in samv71-hal?
aerugo
github_2023
others
4
n7space
Lurkerpas
@@ -0,0 +1,71 @@ +//! System HAL implementation for x86 target. + +use std::convert::TryInto; +use std::time::SystemTime; + +use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; +use bare_metal::CriticalSection; +use once_cell::sync::Lazy; + +use crate::peripherals::Peripherals; + +/// Time when system was started +static TIME_START: Lazy<SystemTime> = Lazy::new(SystemTime::now); + +/// HAL implementation for x86. +pub struct Hal { + /// Hardware peripherals. + _peripherals: Peripherals, +} + +impl Hal { + /// Frequency for the time types (TODO) + const TIMER_FREQ: u32 = 1_000_000; + + /// Create new HAL instance. + pub const fn new(peripherals: Peripherals) -> Self { + Hal { + _peripherals: peripherals, + } + } +} + +impl SystemHal for Hal { + type Instant = crate::time::TimerInstantU64<{ Hal::TIMER_FREQ }>; + type Duration = crate::time::TimerDurationU64<{ Hal::TIMER_FREQ }>; + + fn configure_hardware(&mut self, _config: SystemHardwareConfig) { + todo!() + } + + fn get_system_time(&self) -> Self::Instant { + Self::Instant::from_ticks( + TIME_START + .elapsed() + .expect("{}") + .as_nanos() + .try_into() + .unwrap(), + ) + } + + fn feed_watchdog(&mut self) { + todo!()
Are we planning to implement watchdog on x86? We don't have HW, but we COULD have SW watchtog in another thread....
aerugo
github_2023
others
4
n7space
Lurkerpas
@@ -0,0 +1,56 @@ +//! System HAL implementation for x86 target. + +use aerugo_hal::system_hal::{SystemHal, SystemHardwareConfig}; +use bare_metal::CriticalSection; + +use crate::peripherals::Peripherals; + +/// HAL implementation for x86. +pub struct Hal { + /// Hardware peripherals. + _peripherals: Peripherals, +} + +impl Hal { + /// Frequency for the time types (TODO) + const TIMER_FREQ: u32 = 1_000_000; + + /// Create new HAL instance. + pub const fn new(peripherals: Peripherals) -> Self { + Hal { + _peripherals: peripherals, + } + } +} + +impl SystemHal for Hal { + type Instant = crate::time::TimerInstantU64<{ Hal::TIMER_FREQ }>; + type Duration = crate::time::TimerDurationU64<{ Hal::TIMER_FREQ }>; + + fn configure_hardware(&mut self, _config: SystemHardwareConfig) {
I assume master clock is part of the platform-specific SystemHardwareConfig?
aerugo
github_2023
others
2
n7space
SteelPh0enix
@@ -0,0 +1,114 @@ +//! System control and interface for the user to interact with it. + +pub mod error; + +mod configuration; + +pub use self::configuration::TaskletConfiguration; + +use crate::api::{InitApi, RuntimeApi}; +use crate::boolean_condition::{BooleanConditionSet, BooleanConditionStorage}; +use crate::event::{EventHandle, EventStorage}; +use crate::execution_monitoring::ExecutionStats; +use crate::message_queue::MessageQueueStorage; +use crate::peripherals::Peripherals; +use crate::queue::QueueHandle; +use crate::task::{TaskHandle, TaskId}; +use crate::tasklet::TaskletStorage; + +/// System structure. +pub struct Aerugo {} + +impl Aerugo { + /// Creates new system instance. + pub const fn new() -> Self { + Aerugo {} + } + + /// Starts system scheduler. + pub fn start_scheduler(&self) -> ! { + todo!() + } +} + +impl InitApi for Aerugo { + fn create_tasklet<T, C>( + &'static self, + _config: Self::TaskConfig, + _storage: &'static TaskletStorage<T, C>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_message_queue<T, const N: usize>( + &'static self, + _storage: &'static MessageQueueStorage<T, N>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn create_event(&'static self, _storage: &'static EventStorage) -> Result<(), Self::Error> { + todo!() + } + + fn create_boolean_condition( + &'static self, + _storage: &'static BooleanConditionStorage, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_queue<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _queue: &QueueHandle<T>, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_event<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _event: &EventHandle, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_conditions<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _conditions: BooleanConditionSet, + ) -> Result<(), Self::Error> { + todo!() + } + + fn subscribe_tasklet_to_cyclic<T>( + &'static self, + _tasklet: &TaskHandle<T>, + _period: f64, + ) -> Result<(), Self::Error> { + todo!() + } + + fn init_hardware(&self, _init_fn: fn(&Peripherals)) {
Are you sure that hardware init will be possible via immutable ref to peripherals? I'm aware of the issues with passing mutable arguments to functions via arguments like that, so it'd be good to know if that signature will allow init (or not) right now
aerugo
github_2023
others
2
n7space
SteelPh0enix
@@ -0,0 +1,37 @@ +/// System runtime API. +/// +/// This API can be used by the user in tasklet functions to interact with the system. +use crate::execution_monitoring::ExecutionStats; +use crate::task::TaskId; + +/// System runtime API. +pub trait RuntimeApi: ErrorType { + /// Gets current system time timestamp. + fn get_system_time(&'static self) -> f64; + + /// Sets system time offset. + /// + /// * `offset` - Time offset. + fn set_system_time_offset(&'static self, offset: f64);
maybe `set_system_time` too? to set absolute time value directly? it should be possible to do via offset, so why not give an option to do this directly?