| 1 | //! Real Time Clock (RTC) |
| 2 | mod datetime; |
| 3 | |
| 4 | #[cfg (feature = "low-power" )] |
| 5 | mod low_power; |
| 6 | |
| 7 | #[cfg (feature = "low-power" )] |
| 8 | use core::cell::Cell; |
| 9 | |
| 10 | #[cfg (feature = "low-power" )] |
| 11 | use embassy_sync::blocking_mutex::raw::CriticalSectionRawMutex; |
| 12 | #[cfg (feature = "low-power" )] |
| 13 | use embassy_sync::blocking_mutex::Mutex; |
| 14 | |
| 15 | use self::datetime::{day_of_week_from_u8, day_of_week_to_u8}; |
| 16 | pub use self::datetime::{DateTime, DayOfWeek, Error as DateTimeError}; |
| 17 | use crate::pac::rtc::regs::{Dr, Tr}; |
| 18 | use crate::time::Hertz; |
| 19 | |
| 20 | /// refer to AN4759 to compare features of RTC2 and RTC3 |
| 21 | #[cfg_attr (any(rtc_v1), path = "v1.rs" )] |
| 22 | #[cfg_attr ( |
| 23 | any( |
| 24 | rtc_v2f0, rtc_v2f2, rtc_v2f3, rtc_v2f4, rtc_v2f7, rtc_v2h7, rtc_v2l0, rtc_v2l1, rtc_v2l4, rtc_v2wb |
| 25 | ), |
| 26 | path = "v2.rs" |
| 27 | )] |
| 28 | #[cfg_attr (any(rtc_v3, rtc_v3u5, rtc_v3l5), path = "v3.rs" )] |
| 29 | mod _version; |
| 30 | #[allow (unused_imports)] |
| 31 | pub use _version::*; |
| 32 | use embassy_hal_internal::Peripheral; |
| 33 | |
| 34 | use crate::peripherals::RTC; |
| 35 | |
| 36 | /// Errors that can occur on methods on [RtcClock] |
| 37 | #[non_exhaustive ] |
| 38 | #[derive (Clone, Debug, PartialEq, Eq)] |
| 39 | pub enum RtcError { |
| 40 | /// An invalid DateTime was given or stored on the hardware. |
| 41 | InvalidDateTime(DateTimeError), |
| 42 | |
| 43 | /// The current time could not be read |
| 44 | ReadFailure, |
| 45 | |
| 46 | /// The RTC clock is not running |
| 47 | NotRunning, |
| 48 | } |
| 49 | |
| 50 | /// Provides immutable access to the current time of the RTC. |
| 51 | pub struct RtcTimeProvider { |
| 52 | _private: (), |
| 53 | } |
| 54 | |
| 55 | impl RtcTimeProvider { |
| 56 | /// Return the current datetime. |
| 57 | /// |
| 58 | /// # Errors |
| 59 | /// |
| 60 | /// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`]. |
| 61 | pub fn now(&self) -> Result<DateTime, RtcError> { |
| 62 | self.read(|dr, tr, _| { |
| 63 | let second = bcd2_to_byte((tr.st(), tr.su())); |
| 64 | let minute = bcd2_to_byte((tr.mnt(), tr.mnu())); |
| 65 | let hour = bcd2_to_byte((tr.ht(), tr.hu())); |
| 66 | |
| 67 | let weekday = day_of_week_from_u8(dr.wdu()).map_err(RtcError::InvalidDateTime)?; |
| 68 | let day = bcd2_to_byte((dr.dt(), dr.du())); |
| 69 | let month = bcd2_to_byte((dr.mt() as u8, dr.mu())); |
| 70 | let year = bcd2_to_byte((dr.yt(), dr.yu())) as u16 + 2000_u16; |
| 71 | |
| 72 | DateTime::from(year, month, day, weekday, hour, minute, second).map_err(RtcError::InvalidDateTime) |
| 73 | }) |
| 74 | } |
| 75 | |
| 76 | fn read<R>(&self, mut f: impl FnMut(Dr, Tr, u16) -> Result<R, RtcError>) -> Result<R, RtcError> { |
| 77 | let r = RTC::regs(); |
| 78 | |
| 79 | #[cfg (not(rtc_v2f2))] |
| 80 | let read_ss = || r.ssr().read().ss(); |
| 81 | #[cfg (rtc_v2f2)] |
| 82 | let read_ss = || 0; |
| 83 | |
| 84 | let mut ss = read_ss(); |
| 85 | for _ in 0..5 { |
| 86 | let tr = r.tr().read(); |
| 87 | let dr = r.dr().read(); |
| 88 | let ss_after = read_ss(); |
| 89 | |
| 90 | // If an RTCCLK edge occurs during read we may see inconsistent values |
| 91 | // so read ssr again and see if it has changed. (see RM0433 Rev 7 46.3.9) |
| 92 | if ss == ss_after { |
| 93 | return f(dr, tr, ss.try_into().unwrap()); |
| 94 | } else { |
| 95 | ss = ss_after |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | Err(RtcError::ReadFailure) |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// RTC driver. |
| 104 | pub struct Rtc { |
| 105 | #[cfg (feature = "low-power" )] |
| 106 | stop_time: Mutex<CriticalSectionRawMutex, Cell<Option<low_power::RtcInstant>>>, |
| 107 | _private: (), |
| 108 | } |
| 109 | |
| 110 | /// RTC configuration. |
| 111 | #[non_exhaustive ] |
| 112 | #[derive (Copy, Clone, PartialEq)] |
| 113 | pub struct RtcConfig { |
| 114 | /// The subsecond counter frequency; default is 256 |
| 115 | /// |
| 116 | /// A high counter frequency may impact stop power consumption |
| 117 | pub frequency: Hertz, |
| 118 | } |
| 119 | |
| 120 | impl Default for RtcConfig { |
| 121 | /// LSI with prescalers assuming 32.768 kHz. |
| 122 | /// Raw sub-seconds in 1/256. |
| 123 | fn default() -> Self { |
| 124 | RtcConfig { frequency: Hertz(256) } |
| 125 | } |
| 126 | } |
| 127 | |
| 128 | /// Calibration cycle period. |
| 129 | #[derive (Default, Copy, Clone, Debug, PartialEq)] |
| 130 | #[repr (u8)] |
| 131 | pub enum RtcCalibrationCyclePeriod { |
| 132 | /// 8-second calibration period |
| 133 | Seconds8, |
| 134 | /// 16-second calibration period |
| 135 | Seconds16, |
| 136 | /// 32-second calibration period |
| 137 | #[default] |
| 138 | Seconds32, |
| 139 | } |
| 140 | |
| 141 | impl Rtc { |
| 142 | /// Create a new RTC instance. |
| 143 | pub fn new(_rtc: impl Peripheral<P = RTC>, rtc_config: RtcConfig) -> Self { |
| 144 | #[cfg (not(any(stm32l0, stm32f3, stm32l1, stm32f0, stm32f2)))] |
| 145 | crate::rcc::enable_and_reset::<RTC>(); |
| 146 | |
| 147 | let mut this = Self { |
| 148 | #[cfg (feature = "low-power" )] |
| 149 | stop_time: Mutex::const_new(CriticalSectionRawMutex::new(), Cell::new(None)), |
| 150 | _private: (), |
| 151 | }; |
| 152 | |
| 153 | let frequency = Self::frequency(); |
| 154 | let async_psc = ((frequency.0 / rtc_config.frequency.0) - 1) as u8; |
| 155 | let sync_psc = (rtc_config.frequency.0 - 1) as u16; |
| 156 | |
| 157 | this.configure(async_psc, sync_psc); |
| 158 | |
| 159 | // Wait for the clock to update after initialization |
| 160 | #[cfg (not(rtc_v2f2))] |
| 161 | { |
| 162 | let now = this.time_provider().read(|_, _, ss| Ok(ss)).unwrap(); |
| 163 | while now == this.time_provider().read(|_, _, ss| Ok(ss)).unwrap() {} |
| 164 | } |
| 165 | |
| 166 | this |
| 167 | } |
| 168 | |
| 169 | fn frequency() -> Hertz { |
| 170 | let freqs = unsafe { crate::rcc::get_freqs() }; |
| 171 | freqs.rtc.to_hertz().unwrap() |
| 172 | } |
| 173 | |
| 174 | /// Acquire a [`RtcTimeProvider`] instance. |
| 175 | pub const fn time_provider(&self) -> RtcTimeProvider { |
| 176 | RtcTimeProvider { _private: () } |
| 177 | } |
| 178 | |
| 179 | /// Set the datetime to a new value. |
| 180 | /// |
| 181 | /// # Errors |
| 182 | /// |
| 183 | /// Will return `RtcError::InvalidDateTime` if the datetime is not a valid range. |
| 184 | pub fn set_datetime(&mut self, t: DateTime) -> Result<(), RtcError> { |
| 185 | self.write(true, |rtc| { |
| 186 | let (ht, hu) = byte_to_bcd2(t.hour()); |
| 187 | let (mnt, mnu) = byte_to_bcd2(t.minute()); |
| 188 | let (st, su) = byte_to_bcd2(t.second()); |
| 189 | |
| 190 | let (dt, du) = byte_to_bcd2(t.day()); |
| 191 | let (mt, mu) = byte_to_bcd2(t.month()); |
| 192 | let yr = t.year(); |
| 193 | let yr_offset = (yr - 2000_u16) as u8; |
| 194 | let (yt, yu) = byte_to_bcd2(yr_offset); |
| 195 | |
| 196 | use crate::pac::rtc::vals::Ampm; |
| 197 | |
| 198 | rtc.tr().write(|w| { |
| 199 | w.set_ht(ht); |
| 200 | w.set_hu(hu); |
| 201 | w.set_mnt(mnt); |
| 202 | w.set_mnu(mnu); |
| 203 | w.set_st(st); |
| 204 | w.set_su(su); |
| 205 | w.set_pm(Ampm::AM); |
| 206 | }); |
| 207 | |
| 208 | rtc.dr().write(|w| { |
| 209 | w.set_dt(dt); |
| 210 | w.set_du(du); |
| 211 | w.set_mt(mt > 0); |
| 212 | w.set_mu(mu); |
| 213 | w.set_yt(yt); |
| 214 | w.set_yu(yu); |
| 215 | w.set_wdu(day_of_week_to_u8(t.day_of_week())); |
| 216 | }); |
| 217 | }); |
| 218 | |
| 219 | Ok(()) |
| 220 | } |
| 221 | |
| 222 | /// Return the current datetime. |
| 223 | /// |
| 224 | /// # Errors |
| 225 | /// |
| 226 | /// Will return an `RtcError::InvalidDateTime` if the stored value in the system is not a valid [`DayOfWeek`]. |
| 227 | pub fn now(&self) -> Result<DateTime, RtcError> { |
| 228 | self.time_provider().now() |
| 229 | } |
| 230 | |
| 231 | /// Check if daylight savings time is active. |
| 232 | pub fn get_daylight_savings(&self) -> bool { |
| 233 | let cr = RTC::regs().cr().read(); |
| 234 | cr.bkp() |
| 235 | } |
| 236 | |
| 237 | /// Enable/disable daylight savings time. |
| 238 | pub fn set_daylight_savings(&mut self, daylight_savings: bool) { |
| 239 | self.write(true, |rtc| { |
| 240 | rtc.cr().modify(|w| w.set_bkp(daylight_savings)); |
| 241 | }) |
| 242 | } |
| 243 | |
| 244 | /// Number of backup registers of this instance. |
| 245 | pub const BACKUP_REGISTER_COUNT: usize = RTC::BACKUP_REGISTER_COUNT; |
| 246 | |
| 247 | /// Read content of the backup register. |
| 248 | /// |
| 249 | /// The registers retain their values during wakes from standby mode or system resets. They also |
| 250 | /// retain their value when Vdd is switched off as long as V_BAT is powered. |
| 251 | pub fn read_backup_register(&self, register: usize) -> Option<u32> { |
| 252 | RTC::read_backup_register(RTC::regs(), register) |
| 253 | } |
| 254 | |
| 255 | /// Set content of the backup register. |
| 256 | /// |
| 257 | /// The registers retain their values during wakes from standby mode or system resets. They also |
| 258 | /// retain their value when Vdd is switched off as long as V_BAT is powered. |
| 259 | pub fn write_backup_register(&self, register: usize, value: u32) { |
| 260 | RTC::write_backup_register(RTC::regs(), register, value) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | pub(crate) fn byte_to_bcd2(byte: u8) -> (u8, u8) { |
| 265 | let mut bcd_high: u8 = 0; |
| 266 | let mut value: u8 = byte; |
| 267 | |
| 268 | while value >= 10 { |
| 269 | bcd_high += 1; |
| 270 | value -= 10; |
| 271 | } |
| 272 | |
| 273 | (bcd_high, ((bcd_high << 4) | value)) |
| 274 | } |
| 275 | |
| 276 | pub(crate) fn bcd2_to_byte(bcd: (u8, u8)) -> u8 { |
| 277 | let value: u8 = bcd.1 | bcd.0 << 4; |
| 278 | |
| 279 | let tmp: u8 = ((value & 0xF0) >> 0x4) * 10; |
| 280 | |
| 281 | tmp + (value & 0x0F) |
| 282 | } |
| 283 | |
| 284 | trait SealedInstance { |
| 285 | const BACKUP_REGISTER_COUNT: usize; |
| 286 | |
| 287 | #[cfg (feature = "low-power" )] |
| 288 | #[cfg (not(any(stm32u5, stm32u0)))] |
| 289 | const EXTI_WAKEUP_LINE: usize; |
| 290 | |
| 291 | #[cfg (feature = "low-power" )] |
| 292 | type WakeupInterrupt: crate::interrupt::typelevel::Interrupt; |
| 293 | |
| 294 | fn regs() -> crate::pac::rtc::Rtc { |
| 295 | crate::pac::RTC |
| 296 | } |
| 297 | |
| 298 | /// Read content of the backup register. |
| 299 | /// |
| 300 | /// The registers retain their values during wakes from standby mode or system resets. They also |
| 301 | /// retain their value when Vdd is switched off as long as V_BAT is powered. |
| 302 | fn read_backup_register(rtc: crate::pac::rtc::Rtc, register: usize) -> Option<u32>; |
| 303 | |
| 304 | /// Set content of the backup register. |
| 305 | /// |
| 306 | /// The registers retain their values during wakes from standby mode or system resets. They also |
| 307 | /// retain their value when Vdd is switched off as long as V_BAT is powered. |
| 308 | fn write_backup_register(rtc: crate::pac::rtc::Rtc, register: usize, value: u32); |
| 309 | |
| 310 | // fn apply_config(&mut self, rtc_config: RtcConfig); |
| 311 | } |
| 312 | |