From 8b93dd0c63568acddf43784540aad0bb339ab666 Mon Sep 17 00:00:00 2001 From: bunnie Date: Fri, 9 Apr 2021 05:24:29 +0800 Subject: [PATCH] RTC server now basically working There is an issue with the rtc commandline time checking with respect to unhooking its callback, maybe related to the new disconnect/destroy server code --- Cargo.lock | 2 + services/gam/Cargo.toml | 1 + services/gam/src/status.rs | 51 +++++++++++++++++-- services/llio/src/i2c.rs | 2 + services/llio/src/main.rs | 2 +- services/rtc/Cargo.toml | 3 ++ services/rtc/src/api.rs | 2 +- services/rtc/src/lib.rs | 16 ++++++ services/rtc/src/main.rs | 69 +++++++++++++++++++------- services/shellchat/src/cmds.rs | 8 +-- services/shellchat/src/cmds/rtc_cmd.rs | 31 +++++------- services/shellchat/src/main.rs | 4 +- 12 files changed, 141 insertions(+), 50 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 538090b5a..bc1c2749d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -428,6 +428,7 @@ dependencies = [ "num-derive", "num-traits", "rkyv 0.4.3", + "rtc", "ticktimer-server", "trng", "utralib", @@ -1151,6 +1152,7 @@ name = "rtc" version = "0.1.0" dependencies = [ "bitflags", + "chrono", "heapless", "llio", "log", diff --git a/services/gam/Cargo.toml b/services/gam/Cargo.toml index 652684c61..350f9d3d6 100644 --- a/services/gam/Cargo.toml +++ b/services/gam/Cargo.toml @@ -18,6 +18,7 @@ log = "0.4" log-server = {path = "../log-server"} ticktimer-server = {path = "../ticktimer-server"} trng = {path = "../trng"} +rtc = {path = "../rtc"} xous = {path = "../../xous-rs"} xous-ipc = {path = "../../xous-ipc"} xous-names = {path = "../xous-names"} diff --git a/services/gam/src/status.rs b/services/gam/src/status.rs index f5fe99602..b757e1fb6 100644 --- a/services/gam/src/status.rs +++ b/services/gam/src/status.rs @@ -14,6 +14,9 @@ enum StatusOpcode { // for passing battstats on to the main thread from the callback BattStats, + // for passing DateTime + DateTime, + // indicates time for periodic update of the status bar Pump, } @@ -29,6 +32,14 @@ fn battstats_cb(stats: BattStats) { } } +pub fn dt_callback(dt: rtc::DateTime) { + //log::trace!("dt_callback received with {:?}", dt); + if let Some(cb_to_main_conn) = unsafe{CB_TO_MAIN_CONN} { + let buf = xous_ipc::Buffer::into_buf(dt).or(Err(xous::Error::InternalError)).unwrap(); + buf.lend(cb_to_main_conn, StatusOpcode::DateTime.to_u32().unwrap()).unwrap(); + } +} + pub fn pump_thread(conn: usize) { let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); loop { @@ -102,6 +113,12 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi com.hook_batt_stats(battstats_cb).expect("|status: couldn't hook callback for events from COM"); // prime the loop com.req_batt_stats().expect("Can't get battery stats from COM"); + + let mut rtc = rtc::Rtc::new(&xns).unwrap(); + rtc.hook_rtc_callback(dt_callback).unwrap(); + let mut datetime: Option = None; + let mut dt_pump_modulus = 15; + last_seconds = last_seconds - 1; // this will force the uptime to redraw info!("|status: starting main loop"); loop { @@ -118,21 +135,39 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi } else { write!(&mut battstats_tv, "{}mAh {}%", stats.remaining_capacity, stats.soc).expect("|status: can't write string"); } - stats_phase = (stats_phase + 1) % 8; - gam.post_textview(&mut battstats_tv).expect("|status: can't draw battery stats"); - gam.redraw().expect("|status: couldn't redraw"); }), Some(StatusOpcode::Pump) => { let elapsed_time = ticktimer.elapsed_ms(); let now_seconds: usize = ((elapsed_time / 1000) % 60) as usize; if now_seconds != last_seconds { + dt_pump_modulus += 1; + if dt_pump_modulus > 15 { + dt_pump_modulus = 0; + rtc.request_datetime().expect("|status: can't request datetime from RTC"); + } last_seconds = now_seconds; uptime_tv.clear_str(); - write!(&mut uptime_tv, "Up {:02}:{:02}:{:02}", - (elapsed_time / 3_600_000), (elapsed_time / 60_000) % 60, now_seconds).expect("|status: can't write string"); + if (stats_phase > 3) && datetime.is_some() { + let dt = datetime.unwrap(); + let day = match dt.weekday { + rtc::Weekday::Monday => "Mon", + rtc::Weekday::Tuesday => "Tue", + rtc::Weekday::Wednesday => "Wed", + rtc::Weekday::Thursday => "Thu", + rtc::Weekday::Friday => "Fri", + rtc::Weekday::Saturday => "Sat", + rtc::Weekday::Sunday => "Sun", + }; + write!(&mut uptime_tv, "{:02}:{:02} {} {}/{}", dt.hours, dt.minutes, day, dt.months, dt.days).unwrap(); + } else { + write!(&mut uptime_tv, "Up {:02}:{:02}:{:02}", + (elapsed_time / 3_600_000), (elapsed_time / 60_000) % 60, now_seconds).expect("|status: can't write string"); + } log::trace!("|status: requesting draw of '{}'", uptime_tv); gam.post_textview(&mut uptime_tv).expect("|status: can't draw uptime"); + gam.post_textview(&mut battstats_tv).expect("|status: can't draw battery stats"); gam.redraw().expect("|status: couldn't redraw"); + stats_phase = (stats_phase + 1) % 8; } if elapsed_time - last_time > 500 { //info!("|status: size of TextView type: {} bytes", core::mem::size_of::()); @@ -141,6 +176,12 @@ pub fn status_thread(canvas_gid_0: usize, canvas_gid_1: usize, canvas_gid_2: usi com.req_batt_stats().expect("Can't get battery stats from COM"); } } + Some(StatusOpcode::DateTime) => { + //log::trace!("got DateTime update"); + let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; + let dt = buffer.to_original::().unwrap(); + datetime = Some(dt); + } None => {log::error!("|status: received unknown Opcode"); break} } } diff --git a/services/llio/src/i2c.rs b/services/llio/src/i2c.rs index d0e17186f..03eb21b36 100644 --- a/services/llio/src/i2c.rs +++ b/services/llio/src/i2c.rs @@ -127,6 +127,7 @@ impl I2cStateMachine { } } } + #[allow(dead_code)] // keep this around in case we figure out the NACK issue fn report_nack(&mut self) { log::trace!("NACK"); // report the NACK situation to the listener @@ -251,6 +252,7 @@ impl I2cStateMachine { // we are re-entering from a previous call, store the read value from the previous call rxbuf[self.index as usize - 1] = self.i2c_csr.rf(utra::i2c::RXR_RXR) as u8; log::trace!("READ got 0x{:02x}", rxbuf[self.index as usize - 1]); + self.transaction.rxbuf = Some(rxbuf); } if self.index < self.transaction.rxlen { if self.index == (self.transaction.rxlen - 1) { diff --git a/services/llio/src/main.rs b/services/llio/src/main.rs index 4cbf70e29..7d73af205 100644 --- a/services/llio/src/main.rs +++ b/services/llio/src/main.rs @@ -512,7 +512,7 @@ fn xmain() -> ! { let gpio_base = crate::implementation::log_init(); log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Trace); + log::set_max_level(log::LevelFilter::Info); info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); diff --git a/services/rtc/Cargo.toml b/services/rtc/Cargo.toml index cadf374c6..0598e1f32 100644 --- a/services/rtc/Cargo.toml +++ b/services/rtc/Cargo.toml @@ -23,6 +23,9 @@ rkyv = {version = "0.4.3", default-features = false, features = ["const_generics [target.'cfg(not(any(windows,unix)))'.dependencies] utralib = { path = "../../utralib"} +[target.'cfg(any(windows,unix))'.dependencies] +chrono = "0.4" + [features] debugprint = [] default = [] # "debugprint" diff --git a/services/rtc/src/api.rs b/services/rtc/src/api.rs index 3d6fcf5d0..b7d6ca071 100644 --- a/services/rtc/src/api.rs +++ b/services/rtc/src/api.rs @@ -17,7 +17,7 @@ pub enum TimeUnits { Hours, } -#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)] +#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)] pub struct DateTime { pub seconds: u8, pub minutes: u8, diff --git a/services/rtc/src/lib.rs b/services/rtc/src/lib.rs index c3932ec6e..f4d942084 100644 --- a/services/rtc/src/lib.rs +++ b/services/rtc/src/lib.rs @@ -29,6 +29,20 @@ impl Rtc { let buf = Buffer::into_buf(dt).or(Err(xous::Error::InternalError))?; buf.lend(self.conn, Opcode::SetDateTime.to_u32().unwrap()).map(|_| ()) } + pub fn unhook_rtc_callback(&mut self) -> Result<(), xous::Error> { + if let Some(sid) = self.callback_sid.take() { + // tell my handler thread to quit + let cid = xous::connect(sid).expect("can't connect to CB server for disconnect message"); + let msg = Return::Drop; + let buf = Buffer::into_buf(msg).expect("can't send convert drop message"); + buf.lend(self.conn, 0).expect("can't send Drop message to CB server"); // there is only one message type, so ID field is disregarded + unsafe{xous::disconnect(cid).expect("can't disconnect from CB server");} + xous::destroy_server(sid).expect("can't destroy CB server"); + } + self.callback_sid = None; + unsafe{RTC_CB = None}; + Ok(()) + } pub fn hook_rtc_callback(&mut self, cb: fn(DateTime)) -> Result<(), xous::Error> { log::trace!("hooking rtc callback"); if unsafe{RTC_CB}.is_some() { @@ -113,6 +127,8 @@ fn rtc_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { unsafe { if let Some(cb) = RTC_CB { cb(dt) + } else { + break; } } } diff --git a/services/rtc/src/main.rs b/services/rtc/src/main.rs index 01ad07cdc..b3aa917d2 100644 --- a/services/rtc/src/main.rs +++ b/services/rtc/src/main.rs @@ -454,38 +454,67 @@ mod implementation { // a stub to try to avoid breaking hosted mode for as long as possible. #[cfg(not(target_os = "none"))] mod implementation { - use log::info; use crate::api::Weekday; + use chrono::prelude::*; + use crate::CB_TO_MAIN_CONN; + use num_traits::ToPrimitive; + + fn rtc_thread(sid0: usize, sid1: usize, sid2: usize, sid3: usize) { + let sid = xous::SID::from_u32(sid0 as u32, sid1 as u32, sid2 as u32, sid3 as u32); + log::trace!("rtc callback server started"); + loop { + let msg = xous::receive_message(sid).unwrap(); + log::trace!("rtc callback got msg: {:?}", msg); + // we only have one purpose, and that's to send this message. + if let Some(cb_to_main_conn) = unsafe{CB_TO_MAIN_CONN} { + log::trace!("rtc_get sending time to main server"); + 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, + }; + let dt = crate::api::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, + }; + let buf = xous_ipc::Buffer::into_buf(dt).unwrap(); + buf.send(cb_to_main_conn, crate::api::Opcode::ResponseDateTime.to_u32().unwrap()).unwrap(); + } + } + } pub struct Rtc { - pub seconds: u8, - pub minutes: u8, - pub hours: u8, - pub days: u8, - pub months: u8, - pub years: u8, - pub weekday: Weekday, - updated_ticks: u64, + cb_conn: xous::CID, } impl Rtc { pub fn new(_xns: &xous_names::XousNames) -> Rtc { + let sid = xous::create_server().unwrap(); + let sid_tuple = sid.to_u32(); + let cid = xous::connect(sid).unwrap(); + xous::create_thread_4(rtc_thread, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap(); Rtc { - seconds: 0, - minutes: 0, - hours: 0, - days: 0, - months: 0, - years: 0, - weekday: Weekday::Sunday, - updated_ticks: 0, + cb_conn: cid, } } pub fn rtc_set(&mut self, _secs: u8, _mins: u8, _hours: u8, _days: u8, _months: u8, _years: u8, _day: Weekday) -> Result { Ok(true) } - pub fn rtc_get(&mut self) -> Result<(), xous::Error> { Ok(()) } + pub fn rtc_get(&mut self) -> Result<(), xous::Error> { + xous::send_message(self.cb_conn, xous::Message::new_scalar(0, 0, 0, 0, 0)).unwrap(); + Ok(()) + } pub fn wakeup_alarm(&mut self, _seconds: u8) { } pub fn clear_wakeup_alarm(&mut self) { } pub fn rtc_alarm(&mut self, _seconds: u8) { } @@ -499,7 +528,7 @@ fn xmain() -> ! { use crate::implementation::Rtc; log_server::init_wait().unwrap(); - log::set_max_level(log::LevelFilter::Trace); + log::set_max_level(log::LevelFilter::Info); log::info!("my PID is {}", xous::process::id()); let xns = xous_names::XousNames::new().unwrap(); @@ -574,6 +603,7 @@ fn xmain() -> ! { let outgoing_buf = Buffer::into_buf(ret).or(Err(xous::Error::InternalError)).unwrap(); for maybe_conn in dt_cb_conns.iter_mut() { if let Some(conn) = maybe_conn { + //log::trace!("ResponeDateTime sending to {}", *conn); match outgoing_buf.lend(*conn, 0) { // the ID field is ignored on the callback server Err(xous::Error::ServerNotFound) => { *maybe_conn = None @@ -583,6 +613,7 @@ fn xmain() -> ! { } } } + //log::trace!("ResponeDateTime done"); }, Some(Opcode::RequestDateTime) => { let mut sent = false; diff --git a/services/shellchat/src/cmds.rs b/services/shellchat/src/cmds.rs index 356dd3454..e83f9cc63 100644 --- a/services/shellchat/src/cmds.rs +++ b/services/shellchat/src/cmds.rs @@ -59,7 +59,7 @@ pub struct CommonEnv { ///// 1. add your module here, and pull its namespace into the local crate mod echo; use echo::*; -mod test; use test::*; +//mod test; use test::*; mod sleep; use sleep::*; mod sensors; use sensors::*; //mod callback; use callback::*; @@ -70,7 +70,7 @@ pub struct CmdEnv { common_env: CommonEnv, lastverb: String::<256>, ///// 2. declare storage for your command here. - test_cmd: Test, + //test_cmd: Test, sleep_cmd: Sleep, sensors_cmd: Sensors, //callback_cmd: CallBack, @@ -88,7 +88,7 @@ impl CmdEnv { }, lastverb: String::<256>::new(), ///// 3. initialize your storage, by calling new() - test_cmd: Test::new(), + //test_cmd: Test::new(), sleep_cmd: Sleep::new(), sensors_cmd: Sensors::new(), //callback_cmd: CallBack::new(), @@ -103,7 +103,7 @@ impl CmdEnv { let commands: &mut [& mut dyn ShellCmdApi] = &mut [ ///// 4. add your command to this array, so that it can be looked up and dispatched &mut echo_cmd, - &mut self.test_cmd, + //&mut self.test_cmd, &mut self.sleep_cmd, &mut self.sensors_cmd, //&mut self.callback_cmd, diff --git a/services/shellchat/src/cmds/rtc_cmd.rs b/services/shellchat/src/cmds/rtc_cmd.rs index 4aee01339..3821807df 100644 --- a/services/shellchat/src/cmds/rtc_cmd.rs +++ b/services/shellchat/src/cmds/rtc_cmd.rs @@ -9,6 +9,8 @@ pub fn dt_callback(dt: rtc::DateTime) { //log::info!("got datetime: {:?}", dt); let buf = xous_ipc::Buffer::into_buf(dt).or(Err(xous::Error::InternalError)).unwrap(); buf.lend(callback_conn, 0xdeadbeef).unwrap(); + + unsafe{xous::disconnect(callback_conn).unwrap()}; } #[derive(Debug)] @@ -17,8 +19,7 @@ pub struct RtcCmd { } impl RtcCmd { pub fn new(xns: &xous_names::XousNames) -> Self { - let mut rtc = rtc::Rtc::new(&xns).unwrap(); - rtc.hook_rtc_callback(dt_callback).unwrap(); + let rtc = rtc::Rtc::new(&xns).unwrap(); RtcCmd { rtc, } @@ -38,6 +39,7 @@ impl<'a> ShellCmdApi<'a> for RtcCmd { match sub_cmd { "get" => { write!(ret, "{}", "Requesting DateTime from RTC...").unwrap(); + self.rtc.hook_rtc_callback(dt_callback).unwrap(); self.rtc.request_datetime().unwrap(); }, "set" => { @@ -69,13 +71,13 @@ impl<'a> ShellCmdApi<'a> for RtcCmd { } if let Some(tok_str) = tokens.next() { - day = if let Ok(n) = tok_str.parse::() { n } else { success = false; 0 } + month = if let Ok(n) = tok_str.parse::() { n } else { success = false; 0 } } else { success = false; } if let Some(tok_str) = tokens.next() { - month = if let Ok(n) = tok_str.parse::() { n } else { success = false; 0 } + day = if let Ok(n) = tok_str.parse::() { n } else { success = false; 0 } } else { success = false; } @@ -101,7 +103,7 @@ impl<'a> ShellCmdApi<'a> for RtcCmd { success = false; } if !success { - write!(ret, "{}", "usage: rtc set hh mm ss DD MM YY day\n'day' is three-day code, eg. mon tue").unwrap(); + write!(ret, "{}", "usage: rtc set hh mm ss MM DD YY day\n'day' is three-day code, eg. mon tue").unwrap(); } else { let dt = rtc::DateTime { seconds: sec, @@ -112,7 +114,7 @@ impl<'a> ShellCmdApi<'a> for RtcCmd { years: year, weekday, }; - write!(ret, "Setting {}:{}:{}, {}/{}/{}, {:?}", hour, min, sec, day, month, year, weekday).unwrap(); + write!(ret, "Setting {}:{}:{}, {}/{}/{}, {:?}", hour, min, sec, month, day, year, weekday).unwrap(); self.rtc.set_rtc(dt).unwrap(); } }, @@ -132,19 +134,12 @@ impl<'a> ShellCmdApi<'a> for RtcCmd { let buffer = unsafe { xous_ipc::Buffer::from_memory_message(msg.body.memory_message().unwrap()) }; let dt = buffer.to_original::().unwrap(); -/* - let dt = rtc::DateTime { - seconds: 0, - minutes: 0, - hours: 0, - days: 0, - months: 0, - years: 0, - weekday: rtc::Weekday::Friday, - };*/ + let mut ret = String::<1024>::new(); - //write!(ret, "{}", dt.hours); - write!(ret, "{}:{}:{}, {}/{}/{}, {:?}", dt.hours, dt.minutes, dt.seconds, dt.months, dt.days, dt.years, dt.weekday).unwrap(); + write!(ret, "{}:{:02}:{:02}, {}/{}/{}, {:?}", dt.hours, dt.minutes, dt.seconds, dt.months, dt.days, dt.years, dt.weekday).unwrap(); + + // this currently doesn't work, under suspicion of perhaps one of the destroy/disconnect functions not working right + self.rtc.unhook_rtc_callback().expect("can't unhook callback after completion"); Ok(Some(ret)) } diff --git a/services/shellchat/src/main.rs b/services/shellchat/src/main.rs index 2fe708d16..9146b3fe1 100644 --- a/services/shellchat/src/main.rs +++ b/services/shellchat/src/main.rs @@ -235,11 +235,11 @@ fn imef_cb(s: String::<4000>) { fn test_thread() { let xns = xous_names::XousNames::new().unwrap(); let ticktimer = ticktimer_server::Ticktimer::new().unwrap(); - ticktimer.sleep_ms(5000); + ticktimer.sleep_ms(5000).unwrap(); let rtc = rtc::Rtc::new(&xns).unwrap(); loop { rtc.request_datetime().unwrap(); - ticktimer.sleep_ms(2000); + ticktimer.sleep_ms(2000).unwrap(); } }