aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--embassy-stm32/src/low_power.rs48
-rw-r--r--embassy-stm32/src/rtc/mod.rs79
-rw-r--r--embassy-stm32/src/rtc/v2.rs119
-rw-r--r--embassy-stm32/src/time_driver.rs25
4 files changed, 107 insertions, 164 deletions
diff --git a/embassy-stm32/src/low_power.rs b/embassy-stm32/src/low_power.rs
index 964819abb..425362162 100644
--- a/embassy-stm32/src/low_power.rs
+++ b/embassy-stm32/src/low_power.rs
@@ -66,9 +66,6 @@ pub struct Executor {
66 not_send: PhantomData<*mut ()>, 66 not_send: PhantomData<*mut ()>,
67 scb: SCB, 67 scb: SCB,
68 time_driver: &'static RtcDriver, 68 time_driver: &'static RtcDriver,
69 stop_time: embassy_time::Duration,
70 next_alarm: embassy_time::Duration,
71 wfe: u8,
72} 69}
73 70
74impl Executor { 71impl Executor {
@@ -82,9 +79,6 @@ impl Executor {
82 not_send: PhantomData, 79 not_send: PhantomData,
83 scb: cortex_m::Peripherals::steal().SCB, 80 scb: cortex_m::Peripherals::steal().SCB,
84 time_driver: get_driver(), 81 time_driver: get_driver(),
85 stop_time: Duration::from_ticks(0),
86 next_alarm: Duration::from_ticks(u64::MAX),
87 wfe: 0,
88 }); 82 });
89 83
90 EXECUTOR.as_mut().unwrap() 84 EXECUTOR.as_mut().unwrap()
@@ -94,50 +88,8 @@ impl Executor {
94 unsafe fn on_wakeup_irq(&mut self) { 88 unsafe fn on_wakeup_irq(&mut self) {
95 trace!("low power: on wakeup irq"); 89 trace!("low power: on wakeup irq");
96 90
97 if crate::pac::RTC.isr().read().wutf() {
98 trace!("low power: wutf set");
99 } else {
100 trace!("low power: wutf not set");
101 }
102
103 self.time_driver.resume_time(); 91 self.time_driver.resume_time();
104 trace!("low power: resume time"); 92 trace!("low power: resume time");
105
106 crate::interrupt::typelevel::RTC_WKUP::disable();
107
108 // cortex_m::asm::bkpt();
109
110 // let time_elasped = self.rtc.unwrap().stop_wakeup_alarm() - self.last_stop.take().unwrap();
111 //
112 // trace!("low power: {} ms elapsed", time_elasped.as_millis());
113 //
114 // resume_time(time_elasped);
115 // trace!("low power: resume time");
116 //
117 // self.scb.clear_sleepdeep();
118
119 // cortex_m::asm::bkpt();
120 // Self::get_scb().set_sleeponexit();
121 //
122 // return;
123 //
124 // let elapsed = RTC_INSTANT.take().unwrap() - stop_wakeup_alarm();
125 //
126 // STOP_TIME += elapsed;
127 // // let to_next = NEXT_ALARM - STOP_TIME;
128 // let to_next = Duration::from_secs(3);
129 //
130 // trace!("on wakeup irq: to next: {}", to_next);
131 // if to_next > THRESHOLD {
132 // trace!("start wakeup alarm");
133 // RTC_INSTANT.replace(start_wakeup_alarm(to_next));
134 //
135 // trace!("set sleeponexit");
136 // Self::get_scb().set_sleeponexit();
137 // } else {
138 // Self::get_scb().clear_sleeponexit();
139 // Self::get_scb().clear_sleepdeep();
140 // }
141 } 93 }
142 94
143 pub(self) fn stop_with_rtc(&mut self, rtc: &'static Rtc) { 95 pub(self) fn stop_with_rtc(&mut self, rtc: &'static Rtc) {
diff --git a/embassy-stm32/src/rtc/mod.rs b/embassy-stm32/src/rtc/mod.rs
index a6102077a..1f1abb78d 100644
--- a/embassy-stm32/src/rtc/mod.rs
+++ b/embassy-stm32/src/rtc/mod.rs
@@ -1,6 +1,14 @@
1//! RTC peripheral abstraction 1//! RTC peripheral abstraction
2mod datetime; 2mod datetime;
3 3
4#[cfg(feature = "low-power")]
5use core::cell::Cell;
6
7#[cfg(feature = "low-power")]
8use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex;
9#[cfg(feature = "low-power")]
10use embassy_sync::blocking_mutex::Mutex;
11
4pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError}; 12pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError};
5 13
6/// refer to AN4759 to compare features of RTC2 and RTC3 14/// refer to AN4759 to compare features of RTC2 and RTC3
@@ -30,9 +38,73 @@ pub enum RtcError {
30 NotRunning, 38 NotRunning,
31} 39}
32 40
41#[cfg(feature = "low-power")]
42/// Represents an instant in time that can be substracted to compute a duration
43struct RtcInstant {
44 second: u8,
45 subsecond: u16,
46}
47
48#[cfg(feature = "low-power")]
49impl RtcInstant {
50 pub fn now() -> Self {
51 let tr = RTC::regs().tr().read();
52 let tr2 = RTC::regs().tr().read();
53 let ssr = RTC::regs().ssr().read().ss();
54 let ssr2 = RTC::regs().ssr().read().ss();
55
56 let st = bcd2_to_byte((tr.st(), tr.su()));
57 let st2 = bcd2_to_byte((tr2.st(), tr2.su()));
58
59 assert!(st == st2);
60 assert!(ssr == ssr2);
61
62 let _ = RTC::regs().dr().read();
63
64 let subsecond = ssr;
65 let second = st;
66
67 // trace!("rtc: instant now: st, ssr: {}, {}", st, ssr);
68
69 Self { second, subsecond }
70 }
71}
72
73#[cfg(feature = "low-power")]
74impl core::ops::Sub for RtcInstant {
75 type Output = embassy_time::Duration;
76
77 fn sub(self, rhs: Self) -> Self::Output {
78 use embassy_time::{Duration, TICK_HZ};
79
80 let second = if self.second < rhs.second {
81 self.second + 60
82 } else {
83 self.second
84 };
85
86 // TODO: read prescaler
87
88 let self_ticks = second as u32 * 256 + (255 - self.subsecond as u32);
89 let other_ticks = rhs.second as u32 * 256 + (255 - rhs.subsecond as u32);
90 let rtc_ticks = self_ticks - other_ticks;
91
92 // trace!(
93 // "rtc: instant sub: self, other, rtc ticks: {}, {}, {}",
94 // self_ticks,
95 // other_ticks,
96 // rtc_ticks
97 // );
98
99 Duration::from_ticks(((rtc_ticks * TICK_HZ as u32) / 256u32) as u64)
100 }
101}
102
33/// RTC Abstraction 103/// RTC Abstraction
34pub struct Rtc { 104pub struct Rtc {
35 rtc_config: RtcConfig, 105 rtc_config: RtcConfig,
106 #[cfg(feature = "low-power")]
107 stop_time: Mutex<CriticalSectionRawMutex, Cell<Option<RtcInstant>>>,
36} 108}
37 109
38#[derive(Copy, Clone, Debug, PartialEq)] 110#[derive(Copy, Clone, Debug, PartialEq)]
@@ -108,8 +180,15 @@ impl Rtc {
108 pub fn new(_rtc: impl Peripheral<P = RTC>, rtc_config: RtcConfig) -> Self { 180 pub fn new(_rtc: impl Peripheral<P = RTC>, rtc_config: RtcConfig) -> Self {
109 RTC::enable_peripheral_clk(); 181 RTC::enable_peripheral_clk();
110 182
183 #[cfg(not(feature = "low-power"))]
111 let mut rtc_struct = Self { rtc_config }; 184 let mut rtc_struct = Self { rtc_config };
112 185
186 #[cfg(feature = "low-power")]
187 let mut rtc_struct = Self {
188 rtc_config,
189 stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
190 };
191
113 Self::enable(); 192 Self::enable();
114 193
115 rtc_struct.configure(rtc_config); 194 rtc_struct.configure(rtc_config);
diff --git a/embassy-stm32/src/rtc/v2.rs b/embassy-stm32/src/rtc/v2.rs
index 525dc45a2..d73e7083c 100644
--- a/embassy-stm32/src/rtc/v2.rs
+++ b/embassy-stm32/src/rtc/v2.rs
@@ -1,71 +1,12 @@
1use stm32_metapac::rtc::vals::{Init, Osel, Pol}; 1use stm32_metapac::rtc::vals::{Init, Osel, Pol};
2 2
3#[cfg(feature = "low-power")]
4use super::RtcInstant;
3use super::{sealed, RtcClockSource, RtcConfig}; 5use super::{sealed, RtcClockSource, RtcConfig};
4use crate::pac::rtc::Rtc; 6use crate::pac::rtc::Rtc;
5use crate::peripherals::RTC; 7use crate::peripherals::RTC;
6use crate::rtc::sealed::Instance; 8use crate::rtc::sealed::Instance;
7 9
8#[cfg(all(feature = "time", any(stm32wb, stm32f4)))]
9pub struct RtcInstant {
10 ssr: u16,
11 st: u8,
12}
13
14#[cfg(all(feature = "time", any(stm32wb, stm32f4)))]
15impl RtcInstant {
16 pub fn now() -> Self {
17 // TODO: read value twice
18 use crate::rtc::bcd2_to_byte;
19
20 let tr = RTC::regs().tr().read();
21 let tr2 = RTC::regs().tr().read();
22 let ssr = RTC::regs().ssr().read().ss();
23 let ssr2 = RTC::regs().ssr().read().ss();
24
25 let st = bcd2_to_byte((tr.st(), tr.su()));
26 let st2 = bcd2_to_byte((tr2.st(), tr2.su()));
27
28 assert!(st == st2);
29 assert!(ssr == ssr2);
30
31 let _ = RTC::regs().dr().read();
32
33 trace!("rtc: instant now: st, ssr: {}, {}", st, ssr);
34
35 Self { ssr, st }
36 }
37}
38
39#[cfg(all(feature = "time", any(stm32wb, stm32f4)))]
40impl core::ops::Sub for RtcInstant {
41 type Output = embassy_time::Duration;
42
43 fn sub(self, rhs: Self) -> Self::Output {
44 use embassy_time::{Duration, TICK_HZ};
45
46 let st = if self.st < rhs.st { self.st + 60 } else { self.st };
47
48 // TODO: read prescaler
49
50 let self_ticks = st as u32 * 256 + (255 - self.ssr as u32);
51 let other_ticks = rhs.st as u32 * 256 + (255 - rhs.ssr as u32);
52 let rtc_ticks = self_ticks - other_ticks;
53
54 trace!(
55 "rtc: instant sub: self, other, rtc ticks: {}, {}, {}",
56 self_ticks,
57 other_ticks,
58 rtc_ticks
59 );
60
61 Duration::from_ticks(
62 ((((st as u32 * 256 + (255u32 - self.ssr as u32)) - (rhs.st as u32 * 256 + (255u32 - rhs.ssr as u32)))
63 * TICK_HZ as u32) as u32
64 / 256u32) as u64,
65 )
66 }
67}
68
69#[allow(dead_code)] 10#[allow(dead_code)]
70#[derive(Clone, Copy, Debug)] 11#[derive(Clone, Copy, Debug)]
71pub(crate) enum WakeupPrescaler { 12pub(crate) enum WakeupPrescaler {
@@ -165,16 +106,11 @@ impl super::Rtc {
165 106
166 #[allow(dead_code)] 107 #[allow(dead_code)]
167 #[cfg(all(feature = "time", any(stm32wb, stm32f4)))] 108 #[cfg(all(feature = "time", any(stm32wb, stm32f4)))]
168 /// start the wakeup alarm and return the actual duration of the alarm 109 /// start the wakeup alarm and wtih a duration that is as close to but less than
169 /// the actual duration will be the closest value possible that is less 110 /// the requested duration, and record the instant the wakeup alarm was started
170 /// than the requested duration. 111 pub(crate) fn start_wakeup_alarm(&self, requested_duration: embassy_time::Duration) {
171 ///
172 /// note: this api is exposed for testing purposes until low power is implemented.
173 /// it is not intended to be public
174 pub(crate) fn start_wakeup_alarm(&self, requested_duration: embassy_time::Duration) -> RtcInstant {
175 use embassy_time::{Duration, TICK_HZ}; 112 use embassy_time::{Duration, TICK_HZ};
176 113
177 use crate::interrupt::typelevel::Interrupt;
178 use crate::rcc::get_freqs; 114 use crate::rcc::get_freqs;
179 115
180 let rtc_hz = unsafe { get_freqs() }.rtc.unwrap().0 as u64; 116 let rtc_hz = unsafe { get_freqs() }.rtc.unwrap().0 as u64;
@@ -206,47 +142,34 @@ impl super::Rtc {
206 142
207 trace!("rtc: start wakeup alarm for {} ms", duration.as_millis()); 143 trace!("rtc: start wakeup alarm for {} ms", duration.as_millis());
208 144
209 // self.write(false, |regs| { 145 critical_section::with(|cs| assert!(self.stop_time.borrow(cs).replace(Some(RtcInstant::now())).is_none()))
210 // regs.cr().modify(|w| w.set_wutie(false));
211 //
212 // regs.isr().modify(|w| w.set_wutf(false));
213 //
214 // regs.cr().modify(|w| w.set_wutie(true));
215 // });
216 //
217 // trace!("rtc: clear wuf...");
218 // crate::pac::PWR.cr1().modify(|w| w.set_cwuf(true));
219 // while crate::pac::PWR.csr1().read().wuf() {}
220 // trace!("rtc: clear wuf...done");
221 //
222 // crate::pac::PWR
223 // .cr1()
224 // .modify(|w| w.set_pdds(crate::pac::pwr::vals::Pdds::STANDBY_MODE));
225 //
226 // // crate::pac::PWR.cr1().modify(|w| w.set_lpds(true));
227 //
228 // // crate::pac::EXTI.pr(0).modify(|w| w.set_line(22, true));
229 // crate::interrupt::typelevel::RTC_WKUP::unpend();
230
231 RtcInstant::now()
232 } 146 }
233 147
234 #[allow(dead_code)] 148 #[allow(dead_code)]
235 #[cfg(all(feature = "time", any(stm32wb, stm32f4)))] 149 #[cfg(all(feature = "time", any(stm32wb, stm32f4)))]
236 /// stop the wakeup alarm and return the time remaining 150 /// stop the wakeup alarm and return the time elapsed since `start_wakeup_alarm`
237 /// 151 /// was called, otherwise none
238 /// note: this api is exposed for testing purposes until low power is implemented. 152 pub(crate) fn stop_wakeup_alarm(&self) -> Option<embassy_time::Duration> {
239 /// it is not intended to be public 153 use crate::interrupt::typelevel::Interrupt;
240 pub(crate) fn stop_wakeup_alarm(&self) -> RtcInstant { 154
241 trace!("rtc: stop wakeup alarm..."); 155 trace!("rtc: stop wakeup alarm...");
242 156
243 self.write(false, |regs| { 157 self.write(false, |regs| {
244 regs.cr().modify(|w| w.set_wutie(false)); 158 regs.cr().modify(|w| w.set_wutie(false));
245 regs.cr().modify(|w| w.set_wute(false)); 159 regs.cr().modify(|w| w.set_wute(false));
246 regs.isr().modify(|w| w.set_wutf(false)); 160 regs.isr().modify(|w| w.set_wutf(false));
161
162 crate::pac::EXTI.pr(0).modify(|w| w.set_line(22, true));
163 crate::interrupt::typelevel::RTC_WKUP::unpend();
247 }); 164 });
248 165
249 RtcInstant::now() 166 critical_section::with(|cs| {
167 if let Some(stop_time) = self.stop_time.borrow(cs).take() {
168 Some(RtcInstant::now() - stop_time)
169 } else {
170 None
171 }
172 })
250 } 173 }
251 174
252 #[allow(dead_code)] 175 #[allow(dead_code)]
diff --git a/embassy-stm32/src/time_driver.rs b/embassy-stm32/src/time_driver.rs
index 56f42aa96..99d423d08 100644
--- a/embassy-stm32/src/time_driver.rs
+++ b/embassy-stm32/src/time_driver.rs
@@ -15,7 +15,7 @@ use crate::interrupt::typelevel::Interrupt;
15use crate::pac::timer::vals; 15use crate::pac::timer::vals;
16use crate::rcc::sealed::RccPeripheral; 16use crate::rcc::sealed::RccPeripheral;
17#[cfg(feature = "low-power")] 17#[cfg(feature = "low-power")]
18use crate::rtc::{Rtc, RtcInstant}; 18use crate::rtc::Rtc;
19use crate::timer::sealed::{Basic16bitInstance as BasicInstance, GeneralPurpose16bitInstance as Instance}; 19use crate::timer::sealed::{Basic16bitInstance as BasicInstance, GeneralPurpose16bitInstance as Instance};
20use crate::{interrupt, peripherals}; 20use crate::{interrupt, peripherals};
21 21
@@ -140,8 +140,6 @@ pub(crate) struct RtcDriver {
140 alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>, 140 alarms: Mutex<CriticalSectionRawMutex, [AlarmState; ALARM_COUNT]>,
141 #[cfg(feature = "low-power")] 141 #[cfg(feature = "low-power")]
142 rtc: Mutex<CriticalSectionRawMutex, Cell<Option<&'static Rtc>>>, 142 rtc: Mutex<CriticalSectionRawMutex, Cell<Option<&'static Rtc>>>,
143 #[cfg(feature = "low-power")]
144 stop_time: Mutex<CriticalSectionRawMutex, Cell<Option<RtcInstant>>>,
145} 143}
146 144
147const ALARM_STATE_NEW: AlarmState = AlarmState::new(); 145const ALARM_STATE_NEW: AlarmState = AlarmState::new();
@@ -152,8 +150,6 @@ embassy_time::time_driver_impl!(static DRIVER: RtcDriver = RtcDriver {
152 alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]), 150 alarms: Mutex::const_new(CriticalSectionRawMutex::new(), [ALARM_STATE_NEW; ALARM_COUNT]),
153 #[cfg(feature = "low-power")] 151 #[cfg(feature = "low-power")]
154 rtc: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)), 152 rtc: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
155 #[cfg(feature = "low-power")]
156 stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)),
157}); 153});
158 154
159impl RtcDriver { 155impl RtcDriver {
@@ -340,9 +336,8 @@ impl RtcDriver {
340 /// Stop the wakeup alarm, if enabled, and add the appropriate offset 336 /// Stop the wakeup alarm, if enabled, and add the appropriate offset
341 fn stop_wakeup_alarm(&self) { 337 fn stop_wakeup_alarm(&self) {
342 critical_section::with(|cs| { 338 critical_section::with(|cs| {
343 if let Some(stop_time) = self.stop_time.borrow(cs).take() { 339 if let Some(offset) = self.rtc.borrow(cs).get().unwrap().stop_wakeup_alarm() {
344 let current_time = self.rtc.borrow(cs).get().unwrap().stop_wakeup_alarm(); 340 self.add_time(offset);
345 self.add_time(current_time - stop_time);
346 } 341 }
347 }); 342 });
348 } 343 }
@@ -361,17 +356,11 @@ impl RtcDriver {
361 Err(()) 356 Err(())
362 } else { 357 } else {
363 critical_section::with(|cs| { 358 critical_section::with(|cs| {
364 assert!(self 359 self.rtc
365 .stop_time
366 .borrow(cs) 360 .borrow(cs)
367 .replace(Some( 361 .get()
368 self.rtc 362 .unwrap()
369 .borrow(cs) 363 .start_wakeup_alarm(time_until_next_alarm);
370 .get()
371 .unwrap()
372 .start_wakeup_alarm(time_until_next_alarm)
373 ))
374 .is_none());
375 }); 364 });
376 365
377 T::regs_gp16().cr1().modify(|w| w.set_cen(false)); 366 T::regs_gp16().cr1().modify(|w| w.set_cen(false));