Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

create recovery timer mechanism #101

Merged
merged 12 commits into from
Jun 8, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 12 additions & 5 deletions boards/recovery/src/data_manager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ use messages::Message;

const MAIN_HEIGHT: f32 = 876.0; // meters ASL
const HEIGHT_MIN: f32 = 600.0; // meters ASL
const RECOVERY_DATA_POINTS: u8 = 8; // number of barometric altitude readings held by the recovery
// algorithm

pub struct DataManager {
pub air: Option<Air>,
Expand All @@ -18,6 +20,8 @@ pub struct DataManager {
pub gps_vel: Option<GpsVel>,
pub historical_barometer_altitude: HistoryBuffer<(f32, u32), 8>,
pub current_state: Option<RocketStates>,
// each tick represents a minute that passed
pub recovery_counter: u8,
NoahSprenger marked this conversation as resolved.
Show resolved Hide resolved
}

impl DataManager {
Expand All @@ -32,11 +36,12 @@ impl DataManager {
gps_vel: None,
historical_barometer_altitude,
current_state: None,
recovery_counter: 0,
}
}
/// Returns true if the rocket is descending
pub fn is_falling(&self) -> bool {
if self.historical_barometer_altitude.len() < 8 {
if (self.historical_barometer_altitude.len() as u8) < RECOVERY_DATA_POINTS {
return false;
}
let mut buf = self.historical_barometer_altitude.oldest_ordered();
Expand All @@ -56,7 +61,7 @@ impl DataManager {
avg_sum += slope;
prev = i;
}
match avg_sum / 7.0 {
match avg_sum / (RECOVERY_DATA_POINTS as f32 - 1.0) {
// 7 because we have 8 points.
// exclusive range
x if !(-100.0..=-5.0).contains(&x) => {
Expand All @@ -79,7 +84,7 @@ impl DataManager {
None => false,
}
}
pub fn is_landed(&self) -> bool {
pub fn is_landed(&mut self) -> bool {
if self.historical_barometer_altitude.len() < 8 {
return false;
}
Expand All @@ -99,10 +104,12 @@ impl DataManager {
match avg_sum / 7.0 {
// inclusive range
x if (-0.25..=0.25).contains(&x) => {
return true;
if self.recovery_counter >= 15 {
return true;
}
}
_ => {
// continue
self.recovery_counter = 0;
}
}
}
Expand Down
32 changes: 30 additions & 2 deletions boards/recovery/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
use gpio_manager::GPIOManager;
use hal::gpio::{Pin, Pins, PushPullOutput, PB16, PB17};
use hal::prelude::*;
use hal::timer::TimerCounter2;
use mcan::messageram::SharedMemory;
use messages::*;
use state_machine::{StateMachine, StateMachineContext};
Expand All @@ -42,6 +43,7 @@
data_manager: DataManager,
can0: communication::CanDevice0,
gpio: GPIOManager,
recovery_timer: TimerCounter2,
}

#[local]
Expand Down Expand Up @@ -78,7 +80,7 @@

// SAFETY: Misusing the PAC API can break the system.
// This is safe because we only steal the MCLK.
let (_, _, _, _mclk) = unsafe { clocks.pac.steal() };
let (_, _, _, mut mclk) = unsafe { clocks.pac.steal() };

/* CAN config */
let (pclk_can, gclk0) = Pclk::enable(tokens.pclks.can0, gclk0);
Expand All @@ -104,6 +106,13 @@
/* State Machine config */
let state_machine = StateMachine::new();

/* Recovery Timer config */
let (pclk_tc2tc3, gclk0) = Pclk::enable(tokens.pclks.tc2_tc3, gclk0);
let timerclk: hal::clock::v1::Tc2Tc3Clock = pclk_tc2tc3.into();
let mut recovery_timer =
hal::timer::TimerCounter2::tc2_(&timerclk, peripherals.TC2, &mut mclk);
recovery_timer.enable_interrupt();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't want to enable interrupts here, just create the timer object.


NoahSprenger marked this conversation as resolved.
Show resolved Hide resolved
/* Spawn tasks */
run_sm::spawn().ok();
state_send::spawn().ok();
Expand All @@ -120,6 +129,7 @@
data_manager: DataManager::new(),
can0,
gpio,
recovery_timer,
},
Local {
led_green,
Expand All @@ -133,9 +143,27 @@
/// Idle task for when no other tasks are running.
#[idle]
fn idle(_: idle::Context) -> ! {
loop {}

Check warning on line 146 in boards/recovery/src/main.rs

View workflow job for this annotation

GitHub Actions / clippy

empty `loop {}` wastes CPU cycles

warning: empty `loop {}` wastes CPU cycles --> boards/recovery/src/main.rs:146:9 | 146 | loop {} | ^^^^^^^ | = help: you should either use `panic!()` or add a call pausing or sleeping the thread to the loop body = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#empty_loop = note: `#[warn(clippy::empty_loop)]` on by default
}

// interrupt handler for recovery counter
#[task(binds=TC2, shared=[data_manager, recovery_timer])]
fn recovery_counter_tick(mut cx: recovery_counter_tick::Context) {
NoahSprenger marked this conversation as resolved.
Show resolved Hide resolved
cx.shared.recovery_timer.lock(|timer| {
if timer.wait().is_ok() {
cx.shared.data_manager.lock(|data| {
data.recovery_counter += 1;
});
}
// restart timer after interrupt
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This logic should be inside the if statement, not outside of it. This is because the timer interrupt can fire for multiple reasons and right now you are restarting the time for any and all interrupts, not just the case that it is finished.

let duration_mins = atsamd_hal::fugit::MinutesDurationU32::minutes(1);
// timer requires specific duration format
let timer_duration: atsamd_hal::fugit::Duration<u32, 1, 1000000000> = duration_mins.convert();
timer.enable_interrupt(); // clear interrupt
timer.start(timer_duration);
});
}

#[task(priority = 3, local = [fired: bool = false], shared=[gpio, &em])]
fn fire_drogue(mut cx: fire_drogue::Context) {
cx.shared.em.run(|| {
Expand Down Expand Up @@ -175,7 +203,7 @@

/// Runs the state machine.
/// This takes control of the shared resources.
#[task(priority = 3, local = [state_machine], shared = [can0, gpio, data_manager, &em])]
#[task(priority = 3, local = [state_machine], shared = [can0, gpio, data_manager, &em, recovery_timer])]
fn run_sm(mut cx: run_sm::Context) {
cx.local.state_machine.run(&mut StateMachineContext {
shared_resources: &mut cx.shared,
Expand Down
5 changes: 5 additions & 0 deletions boards/recovery/src/state_machine/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@
use messages::state;
use rtic::Mutex;
pub use states::Initializing;
use atsamd_hal::timer::TimerCounter2;

pub trait StateMachineSharedResources {
fn lock_can(&mut self, f: &dyn Fn(&mut CanDevice0));

Check warning on line 18 in boards/recovery/src/state_machine/mod.rs

View workflow job for this annotation

GitHub Actions / All

methods `lock_can`, `lock_data_manager`, `lock_gpio`, and `lock_recovery_timer` are never used

Check warning on line 18 in boards/recovery/src/state_machine/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

methods `lock_can`, `lock_data_manager`, `lock_gpio`, and `lock_recovery_timer` are never used

warning: methods `lock_can`, `lock_data_manager`, `lock_gpio`, and `lock_recovery_timer` are never used --> boards/recovery/src/state_machine/mod.rs:18:8 | 17 | pub trait StateMachineSharedResources { | --------------------------- methods in this trait 18 | fn lock_can(&mut self, f: &dyn Fn(&mut CanDevice0)); | ^^^^^^^^ 19 | fn lock_data_manager(&mut self, f: &dyn Fn(&mut DataManager)); | ^^^^^^^^^^^^^^^^^ 20 | fn lock_gpio(&mut self, f: &dyn Fn(&mut GPIOManager)); | ^^^^^^^^^ 21 | fn lock_recovery_timer(&mut self, f: &dyn Fn(&mut TimerCounter2)); | ^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(dead_code)]` on by default
fn lock_data_manager(&mut self, f: &dyn Fn(&mut DataManager));
fn lock_gpio(&mut self, f: &dyn Fn(&mut GPIOManager));
fn lock_recovery_timer(&mut self, f: &dyn Fn(&mut TimerCounter2));
}

impl<'a> StateMachineSharedResources for crate::app::__rtic_internal_run_smSharedResources<'a> {
Expand All @@ -29,6 +31,9 @@
fn lock_gpio(&mut self, fun: &dyn Fn(&mut GPIOManager)) {
self.gpio.lock(fun)
}
fn lock_recovery_timer(&mut self, fun: &dyn Fn(&mut TimerCounter2)) {
self.recovery_timer.lock(fun)
}
}

pub struct StateMachineContext<'a, 'b> {
Expand Down Expand Up @@ -69,7 +74,7 @@

// All events are found here
pub enum RocketEvents {
DeployDrogue,

Check warning on line 77 in boards/recovery/src/state_machine/mod.rs

View workflow job for this annotation

GitHub Actions / All

variants `DeployDrogue` and `DeployMain` are never constructed

Check warning on line 77 in boards/recovery/src/state_machine/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

variants `DeployDrogue` and `DeployMain` are never constructed

warning: variants `DeployDrogue` and `DeployMain` are never constructed --> boards/recovery/src/state_machine/mod.rs:77:5 | 76 | pub enum RocketEvents { | ------------ variants in this enum 77 | DeployDrogue, | ^^^^^^^^^^^^ 78 | DeployMain, | ^^^^^^^^^^
DeployMain,
}

Expand Down Expand Up @@ -103,7 +108,7 @@
}
}
// Linter: an implementation of From is preferred since it gives you Into<_> for free where the reverse isn't true
impl Into<state::StateData> for RocketStates {

Check warning on line 111 in boards/recovery/src/state_machine/mod.rs

View workflow job for this annotation

GitHub Actions / clippy

an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true

warning: an implementation of `From` is preferred since it gives you `Into<_>` for free where the reverse isn't true --> boards/recovery/src/state_machine/mod.rs:111:1 | 111 | impl Into<state::StateData> for RocketStates { | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = help: `impl From<Local> for Foreign` is allowed by the orphan rules, for more information see https://doc.rust-lang.org/reference/items/implementations.html#trait-implementation-coherence = help: for further information visit https://rust-lang.github.io/rust-clippy/master/index.html#from_over_into = note: `#[warn(clippy::from_over_into)]` on by default help: replace the `Into` implementation with `From<state_machine::RocketStates>` | 111 ~ impl From<RocketStates> for state::StateData { 112 ~ fn from(val: RocketStates) -> Self { 113 ~ match val { |
fn into(self) -> state::StateData {
match self {
RocketStates::Initializing(_) => state::StateData::Initializing,
Expand Down
12 changes: 11 additions & 1 deletion boards/recovery/src/state_machine/states/terminal_descent.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
use super::Descent;
use crate::app::fire_main;
use crate::state_machine::{
RocketStates, State, StateMachineContext, TransitionInto, WaitForRecovery,
RocketStates, State, StateMachineContext, StateMachineSharedResources, TransitionInto, WaitForRecovery

Check warning on line 4 in boards/recovery/src/state_machine/states/terminal_descent.rs

View workflow job for this annotation

GitHub Actions / All

unused import: `StateMachineSharedResources`

Check warning on line 4 in boards/recovery/src/state_machine/states/terminal_descent.rs

View workflow job for this annotation

GitHub Actions / clippy

unused import: `StateMachineSharedResources`

warning: unused import: `StateMachineSharedResources` --> boards/recovery/src/state_machine/states/terminal_descent.rs:4:47 | 4 | RocketStates, State, StateMachineContext, StateMachineSharedResources, TransitionInto, WaitForRecovery | ^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: `#[warn(unused_imports)]` on by default
};
use crate::{no_transition, transition};
use atsamd_hal::timer_traits::InterruptDrivenTimer;
use common_arm::spawn;
use defmt::{write, Format, Formatter};
use rtic::mutex::Mutex;
use atsamd_hal::prelude::_embedded_hal_timer_CountDown;

#[derive(Debug, Clone)]
pub struct TerminalDescent {}
Expand All @@ -17,6 +19,14 @@
spawn!(fire_main)?;
Ok(())
});
// context.shared_resources.
context.shared_resources.recovery_timer.lock(|timer| {
timer.enable_interrupt();
let duration_mins = atsamd_hal::fugit::MinutesDurationU32::minutes(1);
// timer requires specific duration format
let timer_duration: atsamd_hal::fugit::Duration<u32, 1, 1000000000> = duration_mins.convert();
timer.start(timer_duration);
});
}
fn step(&mut self, context: &mut StateMachineContext) -> Option<RocketStates> {
context.shared_resources.data_manager.lock(|data| {
Expand Down
4 changes: 4 additions & 0 deletions boards/recovery/src/state_machine/states/wait_for_recovery.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ use messages::command::{Command, PowerDown, RadioRate, RadioRateChange};
use messages::sender::Sender::SensorBoard;
use messages::Message;
use rtic::mutex::Mutex;
use atsamd_hal::prelude::_atsamd_hal_timer_traits_InterruptDrivenTimer;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you know why this was needed? What is the error if you do not include this?


#[derive(Debug, Clone)]
pub struct WaitForRecovery {}
Expand All @@ -32,6 +33,9 @@ impl State for WaitForRecovery {
})
});
}
context.shared_resources.recovery_timer.lock(|timer| {
timer.disable_interrupt();
})
}
fn step(&mut self, _context: &mut StateMachineContext) -> Option<RocketStates> {
no_transition!() // this is our final resting place. We should also powerdown this board.
Expand Down
Loading