From cda15a1bb3799a57a2343237ffd752eb5bf67a12 Mon Sep 17 00:00:00 2001 From: bunnie Date: Thu, 24 Mar 2022 18:44:06 +0800 Subject: [PATCH] add a routine to convert hw RTC to a seconds count. --- Cargo.lock | 54 ++++++++++++---- services/llio/Cargo.toml | 6 +- services/llio/src/api.rs | 2 +- services/llio/src/api/rtc_api.rs | 73 +++++++++++++++++++++ services/llio/src/main.rs | 106 ++++++++++++++++++++++++++++++- 5 files changed, 225 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index f6aef5a28..77ceadb0f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -748,7 +748,7 @@ dependencies = [ "hex", "log", "packed_simd_2", - "rand", + "rand 0.7.3", "rand_core 0.5.1", "serde", "sha2-loader", @@ -854,7 +854,7 @@ checksum = "c762bae6dcaf24c4c84667b8579785430908723d5c889f469d76a41d59cc7a9d" dependencies = [ "curve25519-dalek", "ed25519", - "rand", + "rand 0.7.3", "sha2", "zeroize", ] @@ -869,7 +869,7 @@ dependencies = [ "ed25519", "hex", "merlin", - "rand", + "rand 0.7.3", "rand_core 0.5.1", "serde", "serde_bytes", @@ -1134,7 +1134,18 @@ checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" dependencies = [ "cfg-if 1.0.0", "libc", - "wasi", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d39cd93900197114fa1fcb7ae84ca742095eed9442088988ae74fa744e930e77" +dependencies = [ + "cfg-if 1.0.0", + "libc", + "wasi 0.10.2+wasi-snapshot-preview1", ] [[package]] @@ -1390,7 +1401,7 @@ dependencies = [ "gdbstub_arch", "hex", "lazy_static", - "rand", + "rand 0.7.3", "rand_chacha 0.3.1", "riscv", "stats_alloc", @@ -1508,6 +1519,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", + "rand 0.8.5", "rkyv", "susres", "ticktimer-server", @@ -1856,7 +1868,7 @@ dependencies = [ "modals", "num-derive", "num-traits", - "rand", + "rand 0.7.3", "rand_chacha 0.3.1", "rand_core 0.5.1", "rkyv", @@ -2008,7 +2020,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" dependencies = [ - "getrandom", + "getrandom 0.1.16", "libc", "rand_chacha 0.2.2", "rand_core 0.5.1", @@ -2016,6 +2028,17 @@ dependencies = [ "rand_pcg", ] +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.3", +] + [[package]] name = "rand_chacha" version = "0.2.2" @@ -2042,7 +2065,7 @@ version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" dependencies = [ - "getrandom", + "getrandom 0.1.16", ] [[package]] @@ -2050,6 +2073,9 @@ name = "rand_core" version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7" +dependencies = [ + "getrandom 0.2.5", +] [[package]] name = "rand_hc" @@ -2654,7 +2680,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", - "rand", + "rand 0.7.3", "rkyv", "susres", "ticktimer-server", @@ -2969,7 +2995,7 @@ dependencies = [ "log-server", "num-derive", "num-traits", - "rand", + "rand 0.7.3", "rand_chacha 0.3.1", "rand_core 0.5.1", "rkyv", @@ -3136,6 +3162,12 @@ version = "0.9.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" +[[package]] +name = "wasi" +version = "0.10.2+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd6fbd9a79829dd1ad0cc20627bf1ed606756a7f77edff7b66b7064f9cb327c6" + [[package]] name = "wasm-bindgen" version = "0.2.74" @@ -3466,7 +3498,7 @@ version = "0.1.0" dependencies = [ "proc-macro2", "quote", - "rand", + "rand 0.7.3", "syn", ] diff --git a/services/llio/Cargo.toml b/services/llio/Cargo.toml index 8b4acac67..03573e6ab 100644 --- a/services/llio/Cargo.toml +++ b/services/llio/Cargo.toml @@ -27,7 +27,11 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics utralib = {path = "../../utralib"} [target.'cfg(any(windows,unix))'.dependencies] -chrono = "0.4" +chrono = "0.4.19" + +[dev-dependencies] +"chrono" = "0.4.19" +"rand" = "0.8.5" [features] debugprint = [] diff --git a/services/llio/src/api.rs b/services/llio/src/api.rs index 49f99a448..8bed65f94 100644 --- a/services/llio/src/api.rs +++ b/services/llio/src/api.rs @@ -134,7 +134,7 @@ pub(crate) enum Opcode { /// clears any RTC alarms that have been set ClearRtcAlarm, /// reads the current RTC count as a value in seconds - GetRtcCount, + GetRtcValue, /// reads the SessionOffset which correlates RTC count and ticktimer's elapsed_time GetSessionOffset, diff --git a/services/llio/src/api/rtc_api.rs b/services/llio/src/api/rtc_api.rs index 09070f291..7144c9d7f 100644 --- a/services/llio/src/api/rtc_api.rs +++ b/services/llio/src/api/rtc_api.rs @@ -201,3 +201,76 @@ pub const ABRTCMC_TIMERA: u8 = 0x11; // no bitflags, register is timer period in seconds, and the period is N / (source clock frequency) pub const ABRTCMC_TIMERB: u8 = 0x13; // no bitflags, register is timer period in seconds, and the period is N / (source clock frequency) + +pub fn rtc_to_seconds(settings: &[u8]) -> Option { + const CTL3: usize = 0; + const SECS: usize = 1; + const MINS: usize = 2; + const HOURS: usize = 3; + const DAYS: usize = 4; + // note 5 is skipped - this is weekdays, and is unused + const MONTHS: usize = 6; + const YEARS: usize = 7; + if (settings[CTL3] != (Control3::BATT_STD_BL_EN).bits()) // power switchover setting should be initialized + || (settings[SECS] & 0x80 != 0) { // clock integrity should be guaranteed + log::error!("RTC is in an uninitialized state!"); + return None; + } + // this is a secondary check -- I have seen RTC return non-sensical time results before + // so this is an extra check above and beyond what's in the datasheet + if (settings[SECS] > 59) + || (settings[MINS] > 59) + || (settings[HOURS] > 23) // 24 hour mode is default and assumed + || (settings[DAYS] > 31) || (settings[DAYS] == 0) + || (settings[MONTHS] > 12) || (settings[MONTHS] == 0) + || (settings[YEARS] > 99) { + log::error!("RTC has invalid digits!"); + return None; + } + let mut total_secs: u64 = 0; + total_secs += settings[SECS] as u64; + total_secs += settings[MINS] as u64 * 60; + total_secs += settings[HOURS] as u64 * 3600; + const SECS_PER_DAY: u64 = 86400; + // DAYS is checked to be 1-31, so, it's safe to subtract 1 here + total_secs += (settings[DAYS] as u64 - 1) * SECS_PER_DAY; + // this will iterate from 0 through 11; december never has an offset added, because its contribution is directly measured in DAYS + for month in 0..settings[MONTHS] { + match month { + 0 => total_secs += 0u64, + 1 => total_secs += 31u64 * SECS_PER_DAY, + 2 => { + // per spec sheet: 1) If the year counter contains a value which is exactly divisible by 4 (including the year 00), + // the AB-RTCMC-32.768kHz-B5ZE-S3 compensates for leap years by adding a 29th day to February. + if (settings[YEARS] % 4) == 0 { + total_secs += 29u64 * SECS_PER_DAY; + } else { + total_secs += 28u64 * SECS_PER_DAY; + }; + }, + 3 => total_secs += 31u64 * SECS_PER_DAY, + 4 => total_secs += 30u64 * SECS_PER_DAY, + 5 => total_secs += 31u64 * SECS_PER_DAY, + 6 => total_secs += 30u64 * SECS_PER_DAY, + 7 => total_secs += 31u64 * SECS_PER_DAY, + 8 => total_secs += 31u64 * SECS_PER_DAY, + 9 => total_secs += 30u64 * SECS_PER_DAY, + 10 => total_secs += 31u64 * SECS_PER_DAY, + 11 => total_secs += 30u64 * SECS_PER_DAY, + // December shoud never be encountered in this loop since it's right-exclusive + _ => panic!("RTC code has an internal error, months encountered an 'impossible' value"), + } + } + // figure out what the last round multiple of leap years was before the current time + let last_leap = (settings[YEARS] - settings[YEARS] % 4) as u64; + // now add the contributions of all these prior years + total_secs += (last_leap / 4) * (365 * 3 + 366) * SECS_PER_DAY; + // now add the contributions of any years since the last round multiple of leap years + if settings[YEARS] % 4 != 0 { + // account for the leap year + total_secs += 366 * SECS_PER_DAY; + // now account for successive years + total_secs += 365 * (((settings[YEARS] % 4) - 1) as u64) * SECS_PER_DAY; + } + Some(total_secs) +} \ No newline at end of file diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 631a78875..8b90dc2fb 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -512,9 +512,35 @@ fn xmain() -> ! { i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL2, &[control2]).expect("RTC access error"); xous::return_scalar(msg.sender, 0).expect("couldn't return to caller"); }), - Some(Opcode::GetRtcCount) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { - // TODO_RTC: implement get_rtc count function - xous::return_scalar2(msg.sender, 0, 0).expect("couldn't return to caller"); + Some(Opcode::GetRtcValue) => msg_blocking_scalar_unpack!(msg, _, _, _, _, { + // There is a possibility that the RTC hardware is actually in an invalid state. + // Thus, this will return a u64 which is formatted as follows: + // [63] - invalid (0 for valid, 1 for invalid) + // [62:0] - time in seconds + // This is okay because 2^63 is much larger than the total number of seconds trackable by the RTC hardware. + // The RTC hardware can only count up to 100 years before rolling over, which is 3.1*10^9 seconds. + // Note that we start the RTC at somewhere between 0-10 years, so in practice, a user can expect between 90-100 years + // of continuous uptime service out of the RTC. + let mut settings = [0u8; 8]; + match i2c.i2c_read(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &mut settings, None) { + Ok(llio::I2cStatus::ResponseReadOk) => {}, + _ => { + log::error!("Couldn't read seconds from RTC!"); + xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); + continue; + }, + }; + let total_secs = match rtc_to_seconds(&settings) { + Some(s) => s, + None => { + xous::return_scalar2(msg.sender, 0x8000_0000, 0).expect("couldn't return to caller"); + continue; + } + }; + xous::return_scalar2(msg.sender, + ((total_secs >> 32) & 0xFFFF_FFFF) as usize, + (total_secs & 0xFFFF_FFFF) as usize, + ).expect("couldn't return to caller"); }), Some(Opcode::GetSessionOffset) => { // TODO_RTC: implement GetSessionOffset @@ -604,3 +630,77 @@ fn send_event(cb_conns: &[Option; 32], which: usize) { }; } } + +// run with `cargo test -- --nocapture --test-threads=1`: +// --nocapture to see the print output (while debugging) +// --test-threads=1 so we can see the output in sequence +#[cfg(test)] +mod tests { + use super::*; + use chrono::{DateTime, Utc}; + use llio::rtc_to_seconds; + use rand::Rng; + + #[test] + fn test_rtc_to_secs() { + let mut rng = rand::thread_rng(); + let rtc_base = DateTime::::from_utc(chrono::NaiveDate::from_ymd(2000, 1, 1) + .and_hms(0, 0, 0), Utc); + + // test every year, every month, every day, with a random time stamp + for year in 0..99 { + for month in 1..=12 { + let days = match month { + 1 => 1..=31, + 2 => if (year % 4) == 0 { + 1..=29 + } else { + 1..=28 + } + 3 => 1..=31, + 4 => 1..=30, + 5 => 1..=31, + 6 => 1..=30, + 7 => 1..=31, + 8 => 1..=31, + 9 => 1..=30, + 10 => 1..=31, + 11 => 1..=30, + 12 => 1..=31, + _ => {panic!("invalid month")}, + }; + for day in days { + let h = rng.gen_range(0..24); + let m = rng.gen_range(0..60); + let s = rng.gen_range(0..60); + let rtc_test = DateTime::::from_utc( + chrono::NaiveDate::from_ymd(2000 + year, month, day) + .and_hms(h, m, s), Utc); + + let diff = rtc_test.signed_duration_since(rtc_base); + let settings = [ + (Control3::BATT_STD_BL_EN).bits(), + s as u8, + m as u8, + h as u8, + day as u8, + 0, + month as u8, + year as u8, + ]; + if diff.num_seconds() != rtc_to_seconds(&settings).unwrap() as i64 { + println!("{} vs {}", diff.num_seconds(), rtc_to_seconds(&settings).unwrap()); + println!("Duration to {}/{}/{}-{}:{}:{} -- {}", + 2000 + year, + month, + day, + h, m, s, + diff.num_seconds() + ); + } + assert!(diff.num_seconds() == rtc_to_seconds(&settings).unwrap() as i64); + } + } + } + } +}