update status to use the new RTC functions for time

Time is replaced with error messages that indicate either time has not
been set ("Set Time"), or the PDDB has not been mounted (it says
"Login?"), if there is an error. otherwise it displays time
in the local timezone.

Time setting is kind of awful in that you have to enter the time
as UTC. And then a timezone as an offset in hours from UTC. It's
very bare-iron.
This commit is contained in:
bunnie 2022-03-27 04:06:42 +08:00
parent 107c63f7c2
commit 340cd89661
5 changed files with 245 additions and 108 deletions

View file

@ -31,12 +31,14 @@ num-derive = {version = "0.3.3", default-features = false}
num-traits = {version = "0.2.14", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
chrono = {version = "0.4.19", default-features = false, features = ["std"]}
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = {path = "../../utralib"}
# short circuit the datetime call on hosted mode
[target.'cfg(any(windows,unix))'.dependencies]
chrono = "0.4"
chrono = "0.4.19"
[features]
debugprint = []

View file

@ -18,6 +18,18 @@
"zh": "运行",
"en-tts": "Up"
},
"stats.set_time": {
"ja": "設定時間",
"en": "Set Time",
"zh": "设置时间",
"en-tts": "Set Time"
},
"stats.mount_pddb": {
"ja": "ログイン?",
"en": "Login? ",
"zh": "登录?",
"en-tts": "Login? "
},
"secnote.usb_unlock": {
"en": " USB unlocked",
"ja": "USBロック解除",
@ -91,10 +103,16 @@
"en-tts": "Sign Xous update"
},
"mainmenu.set_rtc": {
"en": "Set time",
"ja": "時間設定",
"zh": "设置时间",
"en-tts": "Set time"
"en": "Set UTC time",
"ja": "UTC 時間設定",
"zh": "设置UTC时间",
"en-tts": "Set UTC time"
},
"mainmenu.set_tz": {
"en": "Set local timezone offset",
"ja": "タイムゾーンを設定",
"zh": "设置本地时区",
"en-tts": "Set local timezone offset"
},
"mainmenu.pddb": {
"en": "PDDB Submenu",

View file

@ -19,7 +19,7 @@ use graphics_server::api::GlyphStyle;
use locales::t;
use gam::modal::*;
use gam::{GamObjectList, GamObjectType};
use llio::Weekday;
use chrono::prelude::*;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
@ -42,6 +42,8 @@ pub(crate) enum StatusOpcode {
Pump,
/// Pulls up the time setting UI
UxSetTime,
/// Pulls up the time setting UI
UxSetTimeZone,
/// Initiates a reboot
Reboot,
@ -148,7 +150,7 @@ fn xmain() -> ! {
// create a connection for callback hooks
let cb_cid = xous::connect(status_sid).unwrap();
unsafe { CB_TO_MAIN_CONN = Some(cb_cid) };
let pump_run = Arc::new(AtomicBool::new(true));
let pump_run = Arc::new(AtomicBool::new(false));
let pump_conn = xous::connect(status_sid).unwrap();
let _ = thread::spawn({
let pump_run = pump_run.clone();
@ -221,7 +223,6 @@ fn xmain() -> ! {
remaining_capacity: 650,
};
let mut datetime: Option<llio::DateTime> = None;
let llio = llio::Llio::new(&xns);
log::debug!("usb unlock notice...");
@ -336,15 +337,10 @@ fn xmain() -> ! {
// some RTC UX structures
let modals = modals::Modals::new(&xns).unwrap();
let day_of_week_list = [
t!("rtc.monday", xous::LANG),
t!("rtc.tuesday", xous::LANG),
t!("rtc.wednesday", xous::LANG),
t!("rtc.thursday", xous::LANG),
t!("rtc.friday", xous::LANG),
t!("rtc.saturday", xous::LANG),
t!("rtc.sunday", xous::LANG),
];
let timeserver_cid = xous::connect(xous::SID::from_bytes(crate::time::TIME_SERVER_PUBLIC).unwrap()).unwrap();
let localtime = llio::LocalTime::new();
let pddb_poller = pddb::PddbMountPoller::new();
log::debug!("subscribe to wifi updates");
netmgr.wifi_state_subscribe(cb_cid, StatusOpcode::WifiStats.to_u32().unwrap()).unwrap();
let mut wifi_status: WlanStatus = WlanStatus::from_ipc(WlanStatusIpc::default());
@ -361,6 +357,7 @@ fn xmain() -> ! {
}
});
log::info!("|status: starting main loop"); // don't change this -- factory test looks for this exact string
pump_run.store(true, Ordering::Relaxed); // start status thread updating
loop {
let msg = xous::receive_message(status_sid).unwrap();
log::trace!("|status: Message: {:?}", msg);
@ -524,26 +521,7 @@ fn xmain() -> ! {
{
log::trace!("hosted request of date time - short circuiting server call");
use chrono::prelude::*;
use llio::Weekday;
let now = Local::now();
let wday: Weekday = match now.weekday() {
chrono::Weekday::Mon => Weekday::Monday,
chrono::Weekday::Tue => Weekday::Tuesday,
chrono::Weekday::Wed => Weekday::Wednesday,
chrono::Weekday::Thu => Weekday::Thursday,
chrono::Weekday::Fri => Weekday::Friday,
chrono::Weekday::Sat => Weekday::Saturday,
chrono::Weekday::Sun => Weekday::Sunday,
};
datetime = Some(llio::DateTime {
seconds: now.second() as u8,
minutes: now.minute() as u8,
hours: now.hour() as u8,
months: now.month() as u8,
days: now.day() as u8,
years: (now.year() - 2000) as u8,
weekday: wday,
});
}
}
@ -551,18 +529,34 @@ fn xmain() -> ! {
// have to clear the entire rectangle area, because the text has a variable width and dirty text will remain if the text is shortened
gam.draw_rectangle(status_gid, time_rect).ok();
uptime_tv.clear_str();
if let Some(dt) = datetime {
if let Some(timestamp) = localtime.get_local_time_ms() {
// we "say" UTC but actually local time is in whatever the local time is
let dt = chrono::DateTime::<Utc>::from_utc(
NaiveDateTime::from_timestamp(timestamp as i64 / 1000, 0),
chrono::offset::Utc
);
let timestr = dt.format("%H:%M %m/%d").to_string();
// TODO: convert dt to an actual local time using the chrono library
write!(
&mut uptime_tv,
"{:02}:{:02} {}/{}",
dt.hours, dt.minutes, dt.months, dt.days
"{}",
timestr
)
.unwrap();
} else {
write!(
&mut uptime_tv,
"Invalid RTC"
).unwrap();
if pddb_poller.is_mounted_nonblocking() {
write!(
&mut uptime_tv,
"{}",
t!("stats.set_time", xous::LANG)
).unwrap();
} else {
write!(
&mut uptime_tv,
"{}",
t!("stats.mount_pddb", xous::LANG)
).unwrap();
}
}
// use ticktimer, not stats_phase, because stats_phase encodes some phase drift due to task-switching overhead
write!(
@ -598,7 +592,6 @@ fn xmain() -> ! {
let months: u8;
let days: u8;
let years: u8;
let weekday: Weekday;
months = modals.get_text(
t!("rtc.month", xous::LANG),
@ -621,27 +614,7 @@ fn xmain() -> ! {
.parse::<u8>().expect("pre-validated input failed to re-parse!");
log::debug!("got years {}", years);
for dow in day_of_week_list.iter() {
modals.add_list_item(dow).expect("couldn't build day of week list");
}
let payload = modals.get_radiobutton(t!("rtc.day_of_week", xous::LANG)).expect("couldn't get day of week");
weekday =
if payload.as_str() == t!("rtc.monday", xous::LANG) {
Weekday::Monday
} else if payload.as_str() == t!("rtc.tuesday", xous::LANG) {
Weekday::Tuesday
} else if payload.as_str() == t!("rtc.wednesday", xous::LANG) {
Weekday::Wednesday
} else if payload.as_str() == t!("rtc.thursday", xous::LANG) {
Weekday::Thursday
} else if payload.as_str() == t!("rtc.friday", xous::LANG) {
Weekday::Friday
} else if payload.as_str() == t!("rtc.saturday", xous::LANG) {
Weekday::Saturday
} else {
Weekday::Sunday
};
log::debug!("got weekday {:?}", weekday);
modals.show_notification(t!("rtc.bodge", xous::LANG)).expect("couldn't show bodge note");
hours = modals.get_text(
t!("rtc.hour", xous::LANG),
@ -664,20 +637,38 @@ fn xmain() -> ! {
.parse::<u8>().expect("pre-validated input failed to re-parse!");
log::debug!("got seconds {}", secs);
log::info!("Setting time: {}/{}/{} {}:{}:{} {:?}", months, days, years, hours, mins, secs, weekday);
let _dt = llio::DateTime { // TODO_RTC
seconds: secs,
minutes: mins,
hours,
days,
months,
years,
weekday
};
// TODO_RTC
// rtc.set_rtc(dt).expect("couldn't set the current time");
log::info!("Setting time: {}/{}/{} {}:{}:{}", months, days, years, hours, mins, secs);
let new_dt = chrono::Utc.ymd(years as i32 + 2000, months as u32, days as u32)
.and_hms(hours as u32, mins as u32, secs as u32);
xous::send_message(timeserver_cid,
Message::new_scalar(
crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(),
((new_dt.timestamp_millis() as u64) >> 32) as usize,
(new_dt.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize,
0, 0,
)
).expect("couldn't set time");
pump_run.store(true, Ordering::Relaxed); // stop status updates while we do this
}),
Some(StatusOpcode::UxSetTimeZone) => {
pump_run.store(false, Ordering::Relaxed); // stop status updates while we do this
let tz = modals.get_text(
t!("rtc.timezone", xous::LANG),
Some(tz_ux_validator), None
).expect("couldn't get timezone").as_str()
.parse::<f32>().expect("pre-validated input failed to re-parse!");
log::info!("got tz offset {}", tz);
let tzoff_ms = (tz * 3600.0 * 1000.0) as i64;
xous::send_message(timeserver_cid,
Message::new_scalar(
crate::time::TimeOp::SetTzOffsetMs.to_usize().unwrap(),
(tzoff_ms >> 32) as usize,
(tzoff_ms & 0xFFFF_FFFF) as usize,
0, 0,
)
).expect("couldn't set timezone");
pump_run.store(true, Ordering::Relaxed); // stop status updates while we do this
},
Some(StatusOpcode::Reboot) => {
if ((llio.adc_vbus().unwrap() as f64) * 0.005033) > 1.5 {
// power plugged in, do a reboot using a warm boot method
@ -794,6 +785,17 @@ pub(crate) enum ValidatorOp {
UxSeconds,
}
fn tz_ux_validator(input: TextEntryPayload, _opcode: u32) -> Option<ValidatorErr> {
let text_str = input.as_str();
match text_str.parse::<f32>() {
Ok(input) => if input < -12.0 || input > 14.0 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", xous::LANG)));
},
_ => return Some(ValidatorErr::from_str(t!("rtc.integer_err", xous::LANG))),
}
None
}
fn rtc_ux_validator(input: TextEntryPayload, opcode: u32) -> Option<ValidatorErr> {
let text_str = input.as_str();
let input_int = match text_str.parse::<u32>() {

View file

@ -82,6 +82,13 @@ pub fn create_main_menu(keys: Arc<Mutex<RootKeys>>, status_conn: xous::CID, com:
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menuitems.push(MenuItem {
name: String::from_str(t!("mainmenu.set_tz", xous::LANG)),
action_conn: Some(status_conn),
action_opcode: StatusOpcode::UxSetTimeZone.to_u32().unwrap(),
action_payload: MenuPayload::Scalar([0, 0, 0, 0]),
close_on_select: true,
});
menuitems.push(MenuItem {
name: String::from_str(t!("mainmenu.reboot", xous::LANG)),

View file

@ -25,14 +25,14 @@ use std::thread;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use llio::*;
use pddb::Pddb;
use pddb::{Pddb, PddbMountPoller};
use std::io::{Read, Write, Seek, SeekFrom};
use num_traits::*;
/// This is a "well known name" used by `libstd` to connect to the time server
/// Even thought it is "public" nobody connects to it directly, they connect to it via `libstd`
/// hence the scope of the name is private to this crate.
const TIME_SERVER_PUBLIC: &'static [u8; 16] = b"timeserverpublic";
pub const TIME_SERVER_PUBLIC: &'static [u8; 16] = b"timeserverpublic";
/// This is the registered name for a dedicated private API channel to the PDDB for doing the time reset
/// Even though nobody but the PDDB should connect to this, we have to share it publicly so the PDDB can
/// depend upon this constant.
@ -69,6 +69,10 @@ pub(crate) enum TimeOp {
GetLocalTimeMs = 4,
/// Sets the timezone offset, in milliseconds.
SetTzOffsetMs = 5,
/// Query to see if timezone and time relative to UTC have been set.
WallClockTimeInit = 6,
/// Self-poll for PDDB mount
PddbMountPoll = 7,
}
/// Do not modify the discriminants in this structure. They are used in `libstd` directly.
@ -105,6 +109,8 @@ pub fn start_time_server() {
}
let mut start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
let mut start_tt_ms = tt.elapsed_ms();
log::trace!("start_rtc_secs: {}", start_rtc_secs);
log::trace!("start_tt_ms: {}", start_tt_ms);
// register a suspend/resume listener
let sr_cid = xous::connect(priv_sid).expect("couldn't create suspend callback connection");
@ -114,14 +120,76 @@ pub fn start_time_server() {
TimeOp::SusRes as u32,
sr_cid
).expect("couldn't create suspend/resume object");
let pddb = Pddb::new();
pddb.is_mounted_blocking(None);
let self_cid = xous::connect(pub_sid).unwrap();
let pddb_poller = PddbMountPoller::new();
// enqueue a the first mount poll message
xous::send_message(self_cid,
xous::Message::new_scalar(TimeOp::PddbMountPoll.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't check mount poll");
// an initial behavior which just retuns the raw RTC time, until the PDDB is mounted.
let mut temp = 0;
loop {
if pddb_poller.is_mounted_nonblocking() {
log::debug!("PDDB mount detected, transitioning to real-time adjusted server");
break;
}
let msg = xous::receive_message(pub_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(TimeOp::PddbMountPoll) => {
tt.sleep_ms(330).unwrap();
if temp < 10 {
log::trace!("mount poll");
}
temp += 1;
xous::send_message(self_cid,
xous::Message::new_scalar(TimeOp::PddbMountPoll.to_usize().unwrap(), 0, 0, 0, 0)
).expect("couldn't check mount poll");
}
Some(TimeOp::SusRes) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
// resync time on resume
start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
start_tt_ms = tt.elapsed_ms();
}),
Some(TimeOp::HwSync) => {
start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
start_tt_ms = tt.elapsed_ms();
},
Some(TimeOp::GetUtcTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let t =
start_rtc_secs as i64 * 1000i64
+ (tt.elapsed_ms() - start_tt_ms) as i64;
log::debug!("hw only UTC ms {}", t);
xous::return_scalar2(msg.sender,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetUtcTimeMs");
}),
Some(TimeOp::GetLocalTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let t =
start_rtc_secs as i64 * 1000i64
+ (tt.elapsed_ms() - start_tt_ms) as i64;
assert!(t > 0, "time result is negative, this is an error");
log::debug!("hw only local ms {}", t);
xous::return_scalar2(msg.sender,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetLocalTimeMs");
}),
Some(TimeOp::WallClockTimeInit) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
// definitely not initialized
xous::return_scalar(msg.sender, 0).unwrap();
}),
_ => log::warn!("Time server can't handle this message yet: {:?}", msg),
}
}
// once the PDDB is mounted, read in the time zone offsets and then restart the
// loop handler using the offsets.
let mut offset_handle = Pddb::new();
let mut offset_key = offset_handle.get(
TIME_SERVER_DICT,
TIME_SERVER_UTC_OFFSET,
None, false, true,
None, true, true,
Some(8),
None::<fn()>
).expect("couldn't open UTC offset key");
@ -129,7 +197,7 @@ pub fn start_time_server() {
let mut tz_key = tz_handle.get(
TIME_SERVER_DICT,
TIME_SERVER_TZ_OFFSET,
None, false, true,
None, true, true,
Some(8),
None::<fn()>
).expect("couldn't open TZ offset key");
@ -141,9 +209,17 @@ pub fn start_time_server() {
if tz_key.read(&mut tz_buf).unwrap_or(0) == 8 {
tz_offset_ms = i64::from_le_bytes(tz_buf);
}
log::info!("offset_key: {}", utc_offset_ms);
log::info!("tz_key: {}", tz_offset_ms);
log::info!("start_rtc_secs: {}", start_rtc_secs);
log::info!("start_tt_ms: {}", start_tt_ms);
loop {
let msg = xous::receive_message(pub_sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(TimeOp::PddbMountPoll) => {
// do nothing, we're mounted now.
continue;
},
Some(TimeOp::SusRes) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
// resync time on resume
@ -160,32 +236,39 @@ pub fn start_time_server() {
+ (tt.elapsed_ms() - start_tt_ms) as i64
+ utc_offset_ms;
assert!(t > 0, "time result is negative, this is an error");
log::trace!("utc ms {}", t);
xous::return_scalar2(msg.sender,
((t >> 32) & 0xFFFF_FFFF) as usize,
(t & 0xFFFF_FFFF) as usize,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetUtcTimeMs");
}),
Some(TimeOp::GetLocalTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
log::trace!("current offset {}", (start_rtc_secs as i64 * 1000i64 + (tt.elapsed_ms() - start_tt_ms) as i64) / 1000);
let t =
start_rtc_secs as i64 * 1000i64
+ (tt.elapsed_ms() - start_tt_ms) as i64
+ utc_offset_ms
+ tz_offset_ms;
assert!(t > 0, "time result is negative, this is an error");
log::trace!("local since epoch {}", t / 1000);
xous::return_scalar2(msg.sender,
((t >> 32) & 0xFFFF_FFFF) as usize,
(t & 0xFFFF_FFFF) as usize,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetLocalTimeMs");
}),
Some(TimeOp::SetUtcTimeMs) => xous::msg_scalar_unpack!(msg, utc_hi_ms, utc_lo_ms, _, _, {
let utc_time_ms = (utc_hi_ms as i64) << 32 | (utc_lo_ms as i64);
start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
start_tt_ms = tt.elapsed_ms();
log::info!("utc_time: {}", utc_time_ms / 1000);
log::info!("rtc_secs: {}", start_rtc_secs);
log::info!("start_tt_ms: {}", start_tt_ms);
let offset =
utc_time_ms -
(start_rtc_secs as i64) * 1000;
utc_offset_ms = offset;
offset_key.seek(SeekFrom::Start(0)).expect("couldn't seek");
log::info!("setting offset to {} secs", offset / 1000);
assert_eq!(offset_key.write(&offset.to_le_bytes()).unwrap_or(0), 8, "couldn't commit UTC time offset to PDDB");
offset_key.flush().expect("couldn't flush PDDB");
}),
@ -200,11 +283,19 @@ pub fn start_time_server() {
} else {
tz_offset_ms = tz_ms;
tz_key.seek(SeekFrom::Start(0)).expect("couldn't seek");
log::info!("setting tz offset to {} secs", tz_ms / 1000);
assert_eq!(tz_key.write(&tz_ms.to_le_bytes()).unwrap_or(0), 8, "couldn't commit TZ time offset to PDDB");
tz_key.flush().expect("couldn't flush PDDB");
}
}),
_ => log::error!("Time server public thread received unknown opcode: {:?}", msg),
Some(TimeOp::WallClockTimeInit) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
if utc_offset_ms == 0 || tz_offset_ms == 0 {
xous::return_scalar(msg.sender, 0).unwrap();
} else {
xous::return_scalar(msg.sender, 1).unwrap();
}
}),
None => log::error!("Time server public thread received unknown opcode: {:?}", msg),
}
}
}
@ -226,20 +317,21 @@ pub fn start_time_server() {
};
}
if is_rtc_invalid(&settings) {
log::warn!("RTC settings were invalid. Re-initializing! {:?}", settings);
settings[CTL3] = (Control3::BATT_STD_BL_EN).bits();
let mut start_time = trng.get_u64().unwrap();
// set the clock to a random start time from 1 to 10 years into its maximum range of 100 years
settings[SECS] = (start_time & 0xFF) as u8 % 60;
settings[SECS] = to_bcd((start_time & 0xFF) as u8 % 60);
start_time >>= 8;
settings[MINS] = (start_time & 0xFF) as u8 % 60;
settings[MINS] = to_bcd((start_time & 0xFF) as u8 % 60);
start_time >>= 8;
settings[HOURS] = (start_time & 0xFF) as u8 % 24;
settings[HOURS] = to_bcd((start_time & 0xFF) as u8 % 24);
start_time >>= 8;
settings[DAYS] = (start_time & 0xFF) as u8 % 28 + 1;
settings[DAYS] = to_bcd((start_time & 0xFF) as u8 % 28 + 1);
start_time >>= 8;
settings[MONTHS] = (start_time & 0xFF) as u8 % 12 + 1;
settings[MONTHS] = to_bcd((start_time & 0xFF) as u8 % 12 + 1);
start_time >>= 8;
settings[YEARS] = (start_time & 0xFF) as u8 % 10 + 1;
settings[YEARS] = to_bcd((start_time & 0xFF) as u8 % 10 + 1);
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &settings).expect("RTC access error");
}
rtc_checked.store(true, Ordering::SeqCst);
@ -250,17 +342,17 @@ pub fn start_time_server() {
settings[CTL3] = (Control3::BATT_STD_BL_EN).bits();
let mut start_time = trng.get_u64().unwrap();
// set the clock to a random start time from 1 to 10 years into its maximum range of 100 years
settings[SECS] = (start_time & 0xFF) as u8 % 60;
settings[SECS] = to_bcd((start_time & 0xFF) as u8 % 60);
start_time >>= 8;
settings[MINS] = (start_time & 0xFF) as u8 % 60;
settings[MINS] = to_bcd((start_time & 0xFF) as u8 % 60);
start_time >>= 8;
settings[HOURS] = (start_time & 0xFF) as u8 % 24;
settings[HOURS] = to_bcd((start_time & 0xFF) as u8 % 24);
start_time >>= 8;
settings[DAYS] = (start_time & 0xFF) as u8 % 28 + 1;
settings[DAYS] = to_bcd((start_time & 0xFF) as u8 % 28 + 1);
start_time >>= 8;
settings[MONTHS] = (start_time & 0xFF) as u8 % 12 + 1;
settings[MONTHS] = to_bcd((start_time & 0xFF) as u8 % 12 + 1);
start_time >>= 8;
settings[YEARS] = (start_time & 0xFF) as u8 % 10 + 1;
settings[YEARS] = to_bcd((start_time & 0xFF) as u8 % 10 + 1);
i2c.i2c_write(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &settings).expect("RTC access error");
xous::return_scalar(msg.sender, 0).unwrap();
}),
@ -273,11 +365,27 @@ pub fn start_time_server() {
fn is_rtc_invalid(settings: &[u8]) -> bool {
(settings[CTL3] != (Control3::BATT_STD_BL_EN).bits()) // power switchover setting should be initialized
|| (settings[SECS] & 0x80 != 0) // clock integrity should be guaranteed
|| (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)
|| ((settings[SECS] & 0x80) != 0) // clock integrity should be guaranteed
|| (to_binary(settings[SECS]) > 59)
|| (to_binary(settings[MINS]) > 59)
|| (to_binary(settings[HOURS]) > 23) // 24 hour mode is default and assumed
|| (to_binary(settings[DAYS]) > 31) || (to_binary(settings[DAYS]) == 0)
|| (to_binary(settings[MONTHS]) > 12) || (to_binary(settings[MONTHS]) == 0)
|| (to_binary(settings[YEARS]) > 99)
}
fn to_binary(bcd: u8) -> u8 {
(bcd & 0xf) + ((bcd >> 4) * 10)
}
fn to_bcd(binary: u8) -> u8 {
let mut lsd: u8 = binary % 10;
if lsd > 9 {
lsd = 9;
}
let mut msd: u8 = binary / 10;
if msd > 9 {
msd = 9;
}
(msd << 4) | lsd
}