flesh out callback handling of events in LLIO

This commit is contained in:
bunnie 2021-04-07 18:29:50 +08:00
parent 0e8ac6929a
commit 0f9eea10d9
10 changed files with 478 additions and 94 deletions

4
Cargo.lock generated
View file

@ -1154,9 +1154,13 @@ dependencies = [
"heapless",
"log",
"log-server",
"num-derive",
"num-traits",
"rkyv 0.4.3",
"ticktimer-server",
"utralib",
"xous",
"xous-ipc",
"xous-names",
]

View file

@ -156,7 +156,8 @@ pub(crate) enum Opcode {
GpioIntAsFalling, //(u32),
GpioIntPending,
GpioIntEna, //(u32),
//TODO GpioIntSubscribe, //(String<64>), // TODO
GpioIntSubscribe, //(String<64>), // TODO
GpioIntHappened,
/// not tested - set UART mux
UartMux, //(UartType),
@ -200,12 +201,17 @@ pub(crate) enum Opcode {
IrqI2cTxrxDone, // internal API only
/// not tested -- events
//TODO EventComSubscribe, //(String<64>),
//TODO EventRtcSubscribe, //(String<64>),
EventComSubscribe, //(String<64>),
EventRtcSubscribe, //(String<64>),
EventUsbAttachSubscribe, //(String<64>),
//TODO EventComEnable, //(bool),
//TODO EventRtcEnable, //(bool),
//TODO EventUsbAttachEnable, //(bool),
EventComEnable, //(bool),
EventRtcEnable, //(bool),
EventUsbAttachEnable, //(bool),
/// internal from handler to main loop
EventComHappened,
EventRtcHappened,
EventUsbHappened,
}
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub(crate) enum EventCallback {
@ -213,8 +219,14 @@ pub(crate) enum EventCallback {
Drop,
}
/*
Implementation note: we use a ScalarHook with a two-stage message passing so we don't leak
the local SID. The local SID should be considered a secret, and not shared. A two-stage
message passing system creates a dedicated, one-time use server and shares this SID with
the LLIO server, thus protecting the local SID from disclosure.
*/
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub struct ScalarHook {
pub(crate) struct ScalarHook {
pub sid: (u32, u32, u32, u32),
pub id: u32, // ID of the scalar message to send through (e.g. the discriminant of the Enum on the caller's side API)
pub cid: xous::CID, // caller-side connection ID for the scalar message to route to. Created by the caller before hooking.

View file

@ -258,3 +258,17 @@ impl I2cStateMachine {
}
}
}
#[cfg(target_os = "none")]
impl Drop for I2cStateMachine {
fn drop(&mut self) {
for &l in self.listeners.iter() {
if let Some(listener) = l {
let dummy = I2cTransaction::new();
let buf = xous_ipc::Buffer::into_buf(dummy).or(Err(xous::Error::InternalError)).unwrap();
buf.lend(listener, I2cCallback::Drop.to_u32().unwrap()).map(|_|()).unwrap();
unsafe{xous::disconnect(listener).unwrap();}
};
}
}
}

View file

@ -19,6 +19,7 @@ pub struct Llio {
i2c_sid: Option<xous::SID>,
rtc_sid: Option<xous::SID>,
usb_sid: Option<xous::SID>,
gpio_sid: Option<xous::SID>,
}
impl Llio {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
@ -29,6 +30,7 @@ impl Llio {
i2c_sid: None,
rtc_sid: None,
usb_sid: None,
gpio_sid: None,
})
}
// used to hook a callback for I2c responses
@ -162,6 +164,7 @@ impl Llio {
Err(xous::Error::InternalError)
}
}
// USB hooks
pub fn hook_usb_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.usb_sid.is_none() {
let sid = xous::create_server().unwrap();
@ -179,6 +182,78 @@ impl Llio {
Err(xous::Error::MemoryInUse) // can't hook it twice
}
}
pub fn usb_event_enable(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 };
send_message(self.conn,
Message::new_scalar(Opcode::EventUsbAttachEnable.to_usize().unwrap(), arg, 0, 0, 0)
).map(|_| ())
}
// RTC alarm hooks
pub fn hook_rtc_alarm_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.rtc_sid.is_none() {
let sid = xous::create_server().unwrap();
self.rtc_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(rtc_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
let hookdata = ScalarHook {
sid: sid_tuple,
id,
cid,
};
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::EventRtcSubscribe.to_u32().unwrap()).map(|_|())
} else {
Err(xous::Error::MemoryInUse) // can't hook it twice
}
}
pub fn rtc_alarm_enable(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 };
send_message(self.conn,
Message::new_scalar(Opcode::EventRtcEnable.to_usize().unwrap(), arg, 0, 0, 0)
).map(|_| ())
}
// COM IRQ hooks
pub fn hook_com_event_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.com_sid.is_none() {
let sid = xous::create_server().unwrap();
self.com_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(com_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
let hookdata = ScalarHook {
sid: sid_tuple,
id,
cid,
};
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::EventComSubscribe.to_u32().unwrap()).map(|_|())
} else {
Err(xous::Error::MemoryInUse) // can't hook it twice
}
}
pub fn com_event_enable(&self, ena: bool) -> Result<(), xous::Error> {
let arg = if ena { 1 } else { 0 };
send_message(self.conn,
Message::new_scalar(Opcode::EventComEnable.to_usize().unwrap(), arg, 0, 0, 0)
).map(|_| ())
}
// GPIO IRQ hooks
pub fn hook_gpio_event_callback(&mut self, id: u32, cid: CID) -> Result<(), xous::Error> {
if self.gpio_sid.is_none() {
let sid = xous::create_server().unwrap();
self.gpio_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(gpio_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
let hookdata = ScalarHook {
sid: sid_tuple,
id,
cid,
};
let buf = Buffer::into_buf(hookdata).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::GpioIntSubscribe.to_u32().unwrap()).map(|_|())
} else {
Err(xous::Error::MemoryInUse) // can't hook it twice
}
}
}
impl Drop for Llio {
fn drop(&mut self) {
@ -241,4 +316,64 @@ fn usb_cb_server(sid0: usize, sid1: usize, sid2: usize, sid3: usize) {
None => (),
}
}
}
/// handles callback messages that indicate a RTC interrupt has happened, in the library user's process space.
fn rtc_cb_server(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);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32,
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}),
Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
}
/// handles callback messages that indicate a COM interrupt has happened, in the library user's process space.
fn com_cb_server(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);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32,
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}),
Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
}
/// handles callback messages that indicate a GPIO interrupt has happened, in the library user's process space.
fn gpio_cb_server(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);
loop {
let msg = xous::receive_message(sid).unwrap();
match FromPrimitive::from_usize(msg.body.id()) {
Some(EventCallback::Event) => msg_scalar_unpack!(msg, cid, id, _, _, {
// directly pass the scalar message onto the CID with the ID memorized in the original hook
send_message(cid as u32,
Message::new_scalar(id, 0, 0, 0, 0)
).unwrap();
}),
Some(EventCallback::Drop) => {
break; // this exits the loop and kills the thread
}
None => (),
}
}
}

View file

@ -8,7 +8,7 @@ use i2c::*;
use log::{error, info};
use num_traits::FromPrimitive;
use num_traits::{ToPrimitive, FromPrimitive};
use xous_ipc::Buffer;
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack};
@ -38,15 +38,49 @@ mod implementation {
fn handle_event_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
// just clear the pending request for now and return
if xl.event_csr.rf(utra::btevents::EV_PENDING_COM_INT) != 0 {
if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn,
xous::Message::new_scalar(Opcode::EventComHappened.to_usize().unwrap(), 0, 0, 0, 0)).map(|_|()).unwrap();
} else {
log::error!("|handle_event_irq: COM interrupt, but no connection for notification!")
}
}
if xl.event_csr.rf(utra::btevents::EV_PENDING_RTC_INT) != 0 {
if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn,
xous::Message::new_scalar(Opcode::EventRtcHappened.to_usize().unwrap(), 0, 0, 0, 0)).map(|_|()).unwrap();
} else {
log::error!("|handle_event_irq: RTC interrupt, but no connection for notification!")
}
}
xl.event_csr
.wo(utra::btevents::EV_PENDING, xl.event_csr.r(utra::btevents::EV_PENDING));
}
fn handle_gpio_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
// just clear the pending request for now and return
if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn,
xous::Message::new_scalar(Opcode::GpioIntHappened.to_usize().unwrap(),
xl.gpio_csr.r(utra::gpio::EV_PENDING) as _, 0, 0, 0)).map(|_|()).unwrap();
} else {
log::error!("|handle_event_irq: GPIO interrupt, but no connection for notification!")
}
xl.gpio_csr
.wo(utra::gpio::EV_PENDING, xl.gpio_csr.r(utra::gpio::EV_PENDING));
}
fn handle_power_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
if let Some(conn) = xl.handler_conn {
xous::try_send_message(conn,
xous::Message::new_scalar(Opcode::EventUsbHappened.to_usize().unwrap(),
0, 0, 0, 0)).map(|_|()).unwrap();
} else {
log::error!("|handle_event_irq: USB interrupt, but no connection for notification!")
}
xl.power_csr
.wo(utra::power::EV_PENDING, xl.power_csr.r(utra::power::EV_PENDING));
}
// ASSUME: we are only ever handling txrx done interrupts. If implementing ARB interrupts, this needs to be refactored to read the source and dispatch accordingly.
fn handle_i2c_irq(_irq_no: usize, arg: *mut usize) {
let xl = unsafe { &mut *(arg as *mut Llio) };
@ -54,7 +88,7 @@ mod implementation {
xous::try_send_message(conn,
xous::Message::new_scalar(Opcode::IrqI2cTxrxDone.to_usize().unwrap(), 0, 0, 0, 0)).map(|_| ()).unwrap();
} else {
log::error!("LLIO|handle_i2c_irq: TXRX done interrupt, but no connection for notification!");
log::error!("|handle_i2c_irq: TXRX done interrupt, but no connection for notification!");
}
xl.i2c_csr
.wo(utra::i2c::EV_PENDING, xl.i2c_csr.r(utra::i2c::EV_PENDING));
@ -175,6 +209,13 @@ mod implementation {
)
.expect("couldn't claim GPIO irq");
xous::claim_interrupt(
utra::power::POWER_IRQ,
handle_power_irq,
(&mut xl) as *mut Llio as *mut usize,
)
.expect("couldn't claim Power irq");
// disable interrupt, just in case it's enabled from e.g. a warm boot
xl.i2c_csr.wfo(utra::i2c::EV_ENABLE_TXRX_DONE, 0);
xous::claim_interrupt(
@ -360,6 +401,18 @@ mod implementation {
pub fn xadc_gpio2(&self) -> u16 {
self.xadc_csr.rf(utra::trng::XADC_GPIO2_XADC_GPIO2) as u16
}
pub fn rtc_int_ena(&mut self, ena: bool) {
let value = if ena {1} else {0};
self.event_csr.rmwf(utra::btevents::EV_ENABLE_RTC_INT, value);
}
pub fn com_int_ena(&mut self, ena: bool) {
let value = if ena {1} else {0};
self.event_csr.rmwf(utra::btevents::EV_ENABLE_COM_INT, value);
}
pub fn usb_int_ena(&mut self, ena: bool) {
let value = if ena {1} else {0};
self.power_csr.rmwf(utra::power::EV_PENDING_USB_ATTACH, value);
}
}
}
@ -432,6 +485,13 @@ mod implementation {
pub fn xadc_gpio2(&self) -> u16 {
0
}
pub fn rtc_int_ena(self, _ena: bool) {
}
pub fn com_int_ena(self, _ena: bool) {
}
pub fn usb_int_ena(self, _ena: bool) {
}
}
}
@ -467,6 +527,9 @@ fn xmain() -> ! {
let mut i2c_machine = I2cStateMachine::new(ticktimer, llio.get_i2c_base());
let mut usb_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
let mut com_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
let mut rtc_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
let mut gpio_cb_conns: [Option<ScalarCallback>; 32] = [None; 32];
log::trace!("starting main loop");
let mut reboot_requested: bool = false;
@ -629,26 +692,56 @@ fn xmain() -> ! {
Some(Opcode::EventUsbAttachSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
let (s0, s1, s2, s3) = hookdata.sid;
let sid = xous::SID::from_u32(s0, s1, s2, s3);
let server_to_cb_cid = xous::connect(sid).unwrap();
let cb_dat = Some(ScalarCallback {
server_to_cb_cid,
cb_to_client_cid: hookdata.cid,
cb_to_client_id: hookdata.id,
});
let mut found = false;
for entry in usb_cb_conns.iter_mut() {
if entry.is_none() {
*entry = cb_dat;
found = true;
break;
}
}
if !found {
error!("EventUsbAttachSubscribe ran out of space registering callback");
}
do_hook(hookdata, &mut usb_cb_conns);
}
Some(Opcode::EventComSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut com_cb_conns);
}
Some(Opcode::EventRtcSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut rtc_cb_conns);
}
Some(Opcode::GpioIntSubscribe) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let hookdata = buffer.to_original::<ScalarHook, _>().unwrap();
do_hook(hookdata, &mut gpio_cb_conns);
}
Some(Opcode::EventComEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.com_int_ena(false);
} else {
llio.com_int_ena(true);
}
}),
Some(Opcode::EventRtcEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.rtc_int_ena(false);
} else {
llio.rtc_int_ena(true);
}
}),
Some(Opcode::EventUsbAttachEnable) => msg_scalar_unpack!(msg, ena, _, _, _, {
if ena == 0 {
llio.usb_int_ena(false);
} else {
llio.usb_int_ena(true);
}
}),
Some(Opcode::EventComHappened) => {
send_event(&com_cb_conns, 0);
},
Some(Opcode::EventRtcHappened) => {
send_event(&rtc_cb_conns, 0);
},
Some(Opcode::EventUsbHappened) => {
send_event(&usb_cb_conns, 0);
},
Some(Opcode::GpioIntHappened) => msg_scalar_unpack!(msg, channel, _, _, _, {
send_event(&gpio_cb_conns, channel as usize);
}),
None => {
error!("couldn't convert opcode");
break;
@ -657,8 +750,56 @@ fn xmain() -> ! {
}
}
log::trace!("main loop exit, destroying servers");
unhook(&mut com_cb_conns);
unhook(&mut rtc_cb_conns);
unhook(&mut usb_cb_conns);
unhook(&mut gpio_cb_conns);
xns.unregister_server(llio_sid).unwrap();
xous::destroy_server(llio_sid).unwrap();
log::trace!("quitting");
xous::terminate_process(); loop {}
}
fn do_hook(hookdata: ScalarHook, cb_conns: &mut [Option<ScalarCallback>; 32]) {
let (s0, s1, s2, s3) = hookdata.sid;
let sid = xous::SID::from_u32(s0, s1, s2, s3);
let server_to_cb_cid = xous::connect(sid).unwrap();
let cb_dat = Some(ScalarCallback {
server_to_cb_cid,
cb_to_client_cid: hookdata.cid,
cb_to_client_id: hookdata.id,
});
let mut found = false;
for entry in cb_conns.iter_mut() {
if entry.is_none() {
*entry = cb_dat;
found = true;
break;
}
}
if !found {
error!("ran out of space registering callback");
}
}
fn unhook(cb_conns: &mut [Option<ScalarCallback>; 32]) {
for entry in cb_conns.iter_mut() {
if let Some(scb) = entry {
xous::send_message(scb.server_to_cb_cid,
xous::Message::new_blocking_scalar(EventCallback::Drop.to_usize().unwrap(), 0, 0, 0, 0)
).unwrap();
unsafe{xous::disconnect(scb.server_to_cb_cid).unwrap();}
}
*entry = None;
}
}
fn send_event(cb_conns: &[Option<ScalarCallback>; 32], which: usize) {
for entry in cb_conns.iter() {
if let Some(scb) = entry {
// note that the "which" argument is only used for GPIO events, to indicate which pin had the event
xous::send_message(scb.server_to_cb_cid,
xous::Message::new_scalar(EventCallback::Event.to_usize().unwrap(),
scb.cb_to_client_cid as usize, scb.cb_to_client_id as usize, which, 0)
).unwrap();
};
}
}

View file

@ -14,6 +14,11 @@ xous-names = { path = "../xous-names" }
log = "0.4"
bitflags = "1.2.1"
xous-ipc = {path = "../../xous-ipc"}
num-derive = {version = "0.3", default-features = false}
num-traits = {version = "0.2", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = { path = "../../utralib"}

View file

@ -1,5 +1,6 @@
use xous::{Message, ScalarMessage};
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum Weekday {
Sunday,
Monday,
@ -10,12 +11,14 @@ pub enum Weekday {
Saturday,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub enum TimeUnits {
Seconds,
Minutes,
Hours,
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub struct DateTime {
pub seconds: u8,
pub minutes: u8,
@ -26,48 +29,45 @@ pub struct DateTime {
pub weekday: Weekday,
}
#[allow(dead_code)]
#[derive(Debug)]
pub(crate) const SERVER_NAME_RTC: &str = "_Real time clock application server_";
#[derive(Debug, num_derive::FromPrimitive, num_derive::ToPrimitive)]
pub enum Opcode {
/// Get datetime. This will be accurate to +/-2s, as the RTC is updated from hardware
/// once a second.
GetDateTime,
/// register a callback for the datetime
RegisterDateTimeCallback,
/// register a callback for the RTC alarm event
RegisterAlarmCallback,
/// Get datetime. Causes users with registered callbacks to receive the current DateTime
RequestDateTime,
/// sets the datetime
SetDateTime(DateTime),
SetDateTime, //(DateTime),
/// sets a wake-up alarm. This forces the SoC into power-on state, if it happens to be off.
/// primarily used to trigger cold reboots, but could have other reasons
SetWakeupAlarm(u8, TimeUnits),
SetWakeupAlarm, //(u8, TimeUnits),
/// clear any wakeup alarms that have been set
ClearWakeupAlarm,
/// sets an RTC alarm. This just triggers a regular interrupt, no other side-effect
SetRtcAlarm,
/// clears any RTC alarms that have been set
ClearRtcAlarm,
}
impl core::convert::TryFrom<& Message> for Opcode {
type Error = &'static str;
fn try_from(message: & Message) -> Result<Self, Self::Error> {
match message {
Message::BlockingScalar(m) => match m.id {
0 => Ok(Opcode::GetTrng(m.arg1)),
_ => Err("TRNG api: unknown BlockingScalar ID"),
},
_ => Err("TRNG api: unhandled message type"),
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
pub(crate) enum Return {
ReturnDateTime(DateTime),
Drop,
}
impl Into<Message> for Opcode {
fn into(self) -> Message {
match self {
Opcode::GetTrng(count) => Message::BlockingScalar(ScalarMessage {
id: 0,
arg1: count.into(),
arg2: 0,
arg3: 0,
arg4: 0,
}),
// _ => panic!("TRNG api: Opcode type not handled by Into(), refer to helper method"),
}
}
#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize, Copy, Clone)]
pub(crate) struct ScalarHook {
pub sid: (u32, u32, u32, u32),
pub id: u32, // ID of the scalar message to send through (e.g. the discriminant of the Enum on the caller's side API)
pub cid: xous::CID, // caller-side connection ID for the scalar message to route to. Created by the caller before hooking.
}

View file

@ -1,22 +1,100 @@
#![cfg_attr(target_os = "none", no_std)]
pub mod api;
use xous::{CID, send_message};
pub fn get_u32(cid: CID) -> Result<u32, xous::Error> {
let response = send_message(cid, api::Opcode::GetTrng(1).into())?;
if let xous::Result::Scalar2(trng, _) = response {
Ok(trng as u32)
} else {
panic!("unexpected return value: {:#?}", response);
use api::{Return, Opcode}; // if you prefer to map the api into your local namespace
use xous::{send_message, Error, CID, Message, msg_scalar_unpack};
use xous_ipc::{String, Buffer};
use num_traits::{ToPrimitive, FromPrimitive};
pub struct Rtc {
conn: CID,
callback_sid: Option<xous::SID>,
}
static mut RTC_CB: Option<fn(DateTime)> = None;
impl Rtc {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
let conn = xns.request_connection_blocking(api::SERVER_NAME_RTC).expect("Can't connect to RTC");
Ok(Rtc {
conn,
callback_sid: None,
})
}
pub fn set_rtc(&self, dt: DateTime) -> Result<(), xous::Error> {
let buf = Buffer::into_buf(dt).or(Err(xous::Error::InternalError))?;
buf.lend(self.conn, Opcode::SetDateTime.to_u32().unwrap()).map(|_| ())
}
pub fn rtc_callback(&mut self, cb: fn(DateTime)) -> Result<(), xous::Error> {
if unsafe{RTC_CB}.is_some() {
return Err(xous::Error::MemoryInUse)
}
unsafe{RTC_CB = Some(cb)};
if self.callback_sid.is_none() {
let sid = xous::create_server().unwrap();
self.callback_sid = Some(sid);
let sid_tuple = sid.to_u32();
xous::create_thread_4(rtc_cb_server, sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize).unwrap();
xous::send_message(self.conn,
Message::new_scalar(Opcode::RegisterDateTimeCallback.to_usize().unwrap(),
sid_tuple.0 as usize, sid_tuple.1 as usize, sid_tuple.2 as usize, sid_tuple.3 as usize
)).unwrap();
}
Ok(())
}
pub fn request_datetime(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::RequestDateTime.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_|())
}
pub fn set_alarm(&self, seconds_from_now: u8) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::SetWakeupAlarm.to_usize().unwrap(), seconds_from_now as _, 0, 0, 0)
).map(|_|())
}
pub fn clear_alarm(&self) -> Result<(), xous::Error> {
send_message(self.conn,
Message::new_scalar(Opcode::ClearWakeupAlarm.to_usize().unwrap(), 0, 0, 0, 0)
).map(|_|())
}
}
pub fn get_u64(cid: CID) -> Result<u64, xous::Error> {
let response = send_message(cid, api::Opcode::GetTrng(2).into())?;
if let xous::Result::Scalar2(lo, hi) = response {
Ok( lo as u64 | ((hi as u64) << 32) )
} else {
panic!("unexpected return value: {:#?}", response);
impl Drop for Rtc {
fn drop(&mut self) {
// if we have callbacks, destroy the callback server
if let Some(sid) = self.callback_sid.take() {
// tell my handler thread to quit
let cid = xous::connect(sid).unwrap();
let msg = Return::Drop;
let buf = Buffer::into_buf(msg).unwrap();
buf.lend(self.conn, 0).unwrap(); // there is only one message type, so ID field is disregarded
unsafe{xous::disconnect(cid).unwrap();}
xous::destroy_server(sid).unwrap();
}
// now de-allocate myself. It's unsafe because we are responsible to make sure nobody else is using the connection.
// all implementations will need this
unsafe{xous::disconnect(self.conn).unwrap();}
}
}
fn rtc_cb_server(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);
loop {
let msg = xous::receive_message(sid).unwrap();
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let response = buffer.to_original::<Return,_>().unwrap();
match response {
Return::ReturnDateTime(dt) => {
unsafe {
if let Some(cb) = RTC_CB {
cb(dt)
}
}
}
Return::Drop => {
break;
}
}
}
}

View file

@ -4,10 +4,10 @@
mod api;
use api::*;
use core::convert::TryFrom;
use log::{error, info};
use num_traits::FromPrimitive;
use xous_ipc::{String, Buffer};
use api::{Return, Opcode};
use xous::{CID, msg_scalar_unpack, msg_blocking_scalar_unpack};
#[cfg(target_os = "none")]
mod implementation {
@ -374,11 +374,12 @@ fn xmain() -> ! {
use crate::implementation::Rtc;
log_server::init_wait().unwrap();
info!("RTC: my PID is {}", xous::process::id());
log::set_max_level(log::LevelFilter::Trace);
log::info!("RTC: my PID is {}", xous::process::id());
let xns = xous_names::XousNames::new().unwrap();
let rtc_sid = xns.register_name(xous::names::SERVER_NAME_RTC).expect("RTC: can't register server");
info!("RTC: registered with NS -- {:?}", rtc_sid);
let rtc_sid = xns.register_name(api::SERVER_NAME_RTC).expect("RTC: can't register server");
log::trace!("RTC: registered with NS -- {:?}", rtc_sid);
#[cfg(target_os = "none")]
let rtc = Rtc::new();
@ -386,20 +387,16 @@ fn xmain() -> ! {
#[cfg(not(target_os = "none"))]
let mut rtc = Rtc::new();
info!("RTC: ready to accept requests");
let mut cb_conns: [Option<CID>; 32] = [None; 32];
log::trace!("RTC: ready to accept requests");
loop {
let envelope = xous::receive_message(rtc_sid).unwrap();
if let Ok(opcode) = Opcode::try_from(&envelope.body) {
match opcode {
Opcode::GetRtc(count) => {
let val: [u32; 2] = rtc.get_rtc(count);
xous::return_scalar2(envelope.sender, val[0] as _, val[1] as _)
.expect("RTC: couldn't return GetRtc request");
},
let msg = xous::receive_message(rtc_sid).unwrap();
log::trace!("Message: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(Opcode::SetDateTime) => {
let buffer = unsafe { Buffer::from_memory_message(msg.body.memory_message().unwrap()) };
let dt = buffer.as_flat::<DateTime, _>().unwrap();
}
} else {
error!("KBD: couldn't convert opcode");
}
}
// clean up our program

View file

@ -7,8 +7,6 @@ to refer to servers that are not statically bound into the kernel
pub const SERVER_NAME_IME_PLUGIN_SHELL: &str = "_IME shell plugin_";
pub const SERVER_NAME_RTC: &str = "_Real time clock application server_";
/*
Global message IDs