foramt services/dns

This commit is contained in:
bunnie 2024-01-14 22:08:14 +08:00
parent 8ef2d2d8f2
commit e096384f66
6 changed files with 332 additions and 320 deletions

View file

@ -19,7 +19,8 @@ pub(crate) enum Opcode {
/// used internally to update the TTL field, and eventually expire the cache (unless cache is frozen) /// used internally to update the TTL field, and eventually expire the cache (unless cache is frozen)
UpdateTtl = 2, UpdateTtl = 2,
/// issuing this opcode causes all future attempts to change the DNS server configs to be ignored. This also freezes the cache. /// issuing this opcode causes all future attempts to change the DNS server configs to be ignored. This
/// also freezes the cache.
FreezeConfig = 3, FreezeConfig = 3,
/// this allows automatic updates to the DNS server configs based on DHCP. This is the default state. /// this allows automatic updates to the DNS server configs based on DHCP. This is the default state.
@ -52,14 +53,7 @@ pub(crate) enum Opcode {
} }
#[derive( #[derive(
Debug, Debug, num_derive::FromPrimitive, num_derive::ToPrimitive, Archive, Serialize, Deserialize, Copy, Clone,
num_derive::FromPrimitive,
num_derive::ToPrimitive,
Archive,
Serialize,
Deserialize,
Copy,
Clone,
)] )]
#[repr(u16)] #[repr(u16)]
pub enum DnsResponseCode { pub enum DnsResponseCode {

View file

@ -1,39 +1,37 @@
use net::NetIpAddr;
use std::net::ToSocketAddrs; use std::net::ToSocketAddrs;
use net::NetIpAddr;
use crate::DnsResponseCode; use crate::DnsResponseCode;
#[derive(Debug)] #[derive(Debug)]
pub struct Dns { pub struct Dns {}
}
impl Dns { impl Dns {
pub fn new(_xns: &xous_names::XousNames) -> Result<Self, xous::Error> { pub fn new(_xns: &xous_names::XousNames) -> Result<Self, xous::Error> { Ok(Dns {}) }
Ok(Dns {
})
}
/// Checks first to see if the name could be just an IPv4 or IPv6 in string form, /// Checks first to see if the name could be just an IPv4 or IPv6 in string form,
/// then tries to pass it to the DNS resolver. /// then tries to pass it to the DNS resolver.
pub fn lookup(&self, name: &str) -> Result<NetIpAddr, DnsResponseCode> { pub fn lookup(&self, name: &str) -> Result<NetIpAddr, DnsResponseCode> {
log::debug!("looking up {}", name); log::debug!("looking up {}", name);
match (name, 80).to_socket_addrs() { // we throw away the port because we just want the IP address... match (name, 80).to_socket_addrs() {
Ok(mut iter) => { // we throw away the port because we just want the IP address...
match iter.next() { Ok(mut iter) => match iter.next() {
Some(addr) => { Some(addr) => {
log::debug!("{:?}", addr); log::debug!("{:?}", addr);
Ok(NetIpAddr::from(addr)) Ok(NetIpAddr::from(addr))
}, }
None => { None => {
log::debug!("name error"); log::debug!("name error");
Err(DnsResponseCode::NameError) Err(DnsResponseCode::NameError)
} }
} },
}
Err(e) => { Err(e) => {
log::debug!("format error: {:?}", e); log::debug!("format error: {:?}", e);
Err(DnsResponseCode::FormatError) Err(DnsResponseCode::FormatError)
} }
} }
} }
pub fn flush_cache(&self) -> Result<(), xous::Error> { pub fn flush_cache(&self) -> Result<(), xous::Error> {
log::warn!("DNS cache flush not implemented in hosted mode!"); log::warn!("DNS cache flush not implemented in hosted mode!");
Ok(()) Ok(())

View file

@ -1,10 +1,10 @@
#![cfg_attr(target_os = "none", no_std)] #![cfg_attr(target_os = "none", no_std)]
use xous::CID; use std::net::IpAddr;
use xous_ipc::{Buffer, String};
use num_traits::ToPrimitive;
use net::NetIpAddr; use net::NetIpAddr;
use std::net::IpAddr; use num_traits::ToPrimitive;
use xous::CID;
use xous_ipc::{Buffer, String};
use crate::api::*; use crate::api::*;
@ -15,10 +15,10 @@ pub struct Dns {
impl Dns { impl Dns {
pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> { pub fn new(xns: &xous_names::XousNames) -> Result<Self, xous::Error> {
REFCOUNT.fetch_add(1, Ordering::Relaxed); REFCOUNT.fetch_add(1, Ordering::Relaxed);
let conn = xns.request_connection_blocking(crate::api::SERVER_NAME_DNS).expect("Can't connect to Dns server"); let conn = xns
Ok(Dns { .request_connection_blocking(crate::api::SERVER_NAME_DNS)
conn .expect("Can't connect to Dns server");
}) Ok(Dns { conn })
} }
/// Checks first to see if the name could be just an IPv4 or IPv6 in string form, /// Checks first to see if the name could be just an IPv4 or IPv6 in string form,
@ -32,18 +32,16 @@ impl Dns {
buf.lend_mut(self.conn, Opcode::Lookup.to_u32().unwrap()) buf.lend_mut(self.conn, Opcode::Lookup.to_u32().unwrap())
.or(Err(DnsResponseCode::UnknownError))?; .or(Err(DnsResponseCode::UnknownError))?;
let response = buf.to_original::<DnsResponse, _>().or(Err(DnsResponseCode::UnknownError))?; let response = buf.to_original::<DnsResponse, _>().or(Err(DnsResponseCode::UnknownError))?;
if let Some(addr) = response.addr { if let Some(addr) = response.addr { Ok(addr) } else { Err(response.code) }
Ok(addr)
} else {
Err(response.code)
}
} }
} }
pub fn flush_cache(&self) -> Result<(), xous::Error> { pub fn flush_cache(&self) -> Result<(), xous::Error> {
xous::send_message( xous::send_message(
self.conn, self.conn,
xous::Message::new_scalar(Opcode::Flush.to_usize().unwrap(), 0, 0, 0, 0) xous::Message::new_scalar(Opcode::Flush.to_usize().unwrap(), 0, 0, 0, 0),
).map(|_| ()) )
.map(|_| ())
} }
} }
@ -51,13 +49,17 @@ use core::sync::atomic::{AtomicU32, Ordering};
static REFCOUNT: AtomicU32 = AtomicU32::new(0); static REFCOUNT: AtomicU32 = AtomicU32::new(0);
impl Drop for Dns { impl Drop for Dns {
fn drop(&mut self) { fn drop(&mut self) {
// the connection to the server side must be reference counted, so that multiple instances of this object within // the connection to the server side must be reference counted, so that multiple instances of this
// a single process do not end up de-allocating the CID on other threads before they go out of scope. // object within a single process do not end up de-allocating the CID on other threads before
// Note to future me: you want this. Don't get rid of it because you think, "nah, nobody will ever make more than one copy of this object". // they go out of scope. Note to future me: you want this. Don't get rid of it because you
// think, "nah, nobody will ever make more than one copy of this object".
if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 { if REFCOUNT.fetch_sub(1, Ordering::Relaxed) == 1 {
unsafe{xous::disconnect(self.conn).unwrap();} unsafe {
} xous::disconnect(self.conn).unwrap();
// if there was object-specific state (such as a one-time use server for async callbacks, specific to the object instance), }
// de-allocate those items here. They don't need a reference count because they are object-specific }
// if there was object-specific state (such as a one-time use server for async callbacks, specific to
// the object instance), de-allocate those items here. They don't need a reference count
// because they are object-specific
} }
} }

View file

@ -3,18 +3,17 @@
mod api; mod api;
mod time; // why is this here? because it's the only place it'll fit. :-/ mod time; // why is this here? because it's the only place it'll fit. :-/
use api::*;
use net::NetIpAddr;
use num_traits::*;
use xous::msg_scalar_unpack;
use std::collections::HashMap; use std::collections::HashMap;
use std::convert::TryInto; use std::convert::TryInto;
use std::io::ErrorKind; use std::io::ErrorKind;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket}; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, UdpSocket};
use std::time::Duration;
use std::thread; use std::thread;
use std::time::Duration;
use api::*;
use net::NetIpAddr;
use num_traits::*;
use xous::msg_scalar_unpack;
use xous_ipc::{Buffer, String}; use xous_ipc::{Buffer, String};
// KISS DNS // KISS DNS
@ -47,11 +46,7 @@ struct Message {
const FLAG_RD: u16 = 0x0100; // Recursion desired const FLAG_RD: u16 = 0x0100; // Recursion desired
impl Message { impl Message {
pub fn from(datagram: &[u8]) -> Self { pub fn from(datagram: &[u8]) -> Self { Self { datagram: Vec::from(datagram) } }
Self {
datagram: Vec::from(datagram),
}
}
pub fn query(qname: &str, qtype: QueryType, qclass: QueryClass, id: u16) -> Self { pub fn query(qname: &str, qtype: QueryType, qclass: QueryClass, id: u16) -> Self {
let mut datagram = Vec::new(); let mut datagram = Vec::new();
@ -85,21 +80,11 @@ impl Message {
Self { datagram } Self { datagram }
} }
pub fn id(&self) -> u16 { pub fn id(&self) -> u16 { u16::from_be_bytes(self.datagram[0..2].try_into().unwrap()) }
u16::from_be_bytes(self.datagram[0..2].try_into().unwrap())
}
pub fn header(&self) -> u16 { pub fn header(&self) -> u16 { u16::from_be_bytes(self.datagram[2..4].try_into().unwrap()) }
u16::from_be_bytes(self.datagram[2..4].try_into().unwrap())
}
pub fn is_response(&self) -> bool { pub fn is_response(&self) -> bool { if (self.header() & (1 << 15)) == 0 { false } else { true } }
if (self.header() & (1 << 15)) == 0 {
false
} else {
true
}
}
fn fast_foward_name(&self, start: usize) -> Result<usize, DnsResponseCode> { fn fast_foward_name(&self, start: usize) -> Result<usize, DnsResponseCode> {
use DnsResponseCode::FormatError; use DnsResponseCode::FormatError;
@ -156,9 +141,7 @@ impl Message {
// pointer // pointer
index += 1; index += 1;
if self.datagram[index] != 0xc { if self.datagram[index] != 0xc {
log::error!( log::error!("Found aname pointer, but value does not conform to length of aname header");
"Found aname pointer, but value does not conform to length of aname header"
);
return Err(FormatError); return Err(FormatError);
} }
index += 1; index += 1;
@ -195,10 +178,10 @@ impl Message {
log::error!("Got a 4-byte address, but ATYPE != A (1)"); log::error!("Got a 4-byte address, but ATYPE != A (1)");
return Err(FormatError); return Err(FormatError);
} }
// this copy happens because I can't figure out how to get Ipv4Addr::from() to realize it's casting from a [u8;4] // this copy happens because I can't figure out how to get Ipv4Addr::from() to realize
// it's casting from a [u8;4]
let mut rdata: [u8; 4] = [0; 4]; let mut rdata: [u8; 4] = [0; 4];
for (&src, dst) in self.datagram[index..index + 4].iter().zip(rdata.iter_mut()) for (&src, dst) in self.datagram[index..index + 4].iter().zip(rdata.iter_mut()) {
{
*dst = src; *dst = src;
} }
let addr = IpAddr::V4(Ipv4Addr::from(rdata)); let addr = IpAddr::V4(Ipv4Addr::from(rdata));
@ -211,12 +194,10 @@ impl Message {
log::error!("Got a 16-byte address, but ATYPE != AAAA (28)"); log::error!("Got a 16-byte address, but ATYPE != AAAA (28)");
return Err(FormatError); return Err(FormatError);
} }
// this copy happens because I can't figure out how to get Ipv6Addr::from() to realize it's casting from a [u8;4] // this copy happens because I can't figure out how to get Ipv6Addr::from() to realize
// it's casting from a [u8;4]
let mut rdata: [u8; 16] = [0; 16]; let mut rdata: [u8; 16] = [0; 16];
for (&src, dst) in self.datagram[index..index + 16] for (&src, dst) in self.datagram[index..index + 16].iter().zip(rdata.iter_mut()) {
.iter()
.zip(rdata.iter_mut())
{
*dst = src; *dst = src;
} }
let addr = IpAddr::V6(Ipv6Addr::from(rdata)); let addr = IpAddr::V6(Ipv6Addr::from(rdata));
@ -317,9 +298,7 @@ impl Resolver {
pub fn new(xns: &xous_names::XousNames) -> Resolver { pub fn new(xns: &xous_names::XousNames) -> Resolver {
let trng = trng::Trng::new(&xns).unwrap(); let trng = trng::Trng::new(&xns).unwrap();
let local_port = (49152 + trng.get_u32().unwrap() % 16384) as u16; let local_port = (49152 + trng.get_u32().unwrap() % 16384) as u16;
let socket = UdpSocket::bind( let socket = UdpSocket::bind(format!("0.0.0.0:{}", local_port))
format!("0.0.0.0:{}", local_port),
)
.expect("couldn't create socket for DNS resolver"); .expect("couldn't create socket for DNS resolver");
let timeout = Duration::from_millis(10_000); // 10 seconds for DNS to resolve by default let timeout = Duration::from_millis(10_000); // 10 seconds for DNS to resolve by default
socket.set_read_timeout(Some(timeout)).unwrap(); socket.set_read_timeout(Some(timeout)).unwrap();
@ -336,26 +315,23 @@ impl Resolver {
freeze: false, freeze: false,
} }
} }
pub fn add_server(&mut self, addr: IpAddr) {
self.mgr.add_server(addr); pub fn add_server(&mut self, addr: IpAddr) { self.mgr.add_server(addr); }
}
pub fn remove_server(&mut self, addr: IpAddr) { pub fn remove_server(&mut self, addr: IpAddr) { self.mgr.remove_server(addr); }
self.mgr.remove_server(addr);
} pub fn clear_all_servers(&mut self) { self.mgr.clear(); }
pub fn clear_all_servers(&mut self) {
self.mgr.clear();
}
pub fn set_freeze_config(&mut self, freeze: bool) { pub fn set_freeze_config(&mut self, freeze: bool) {
self.freeze = freeze; self.freeze = freeze;
self.mgr.set_freeze(freeze); self.mgr.set_freeze(freeze);
} }
pub fn get_freeze(&self) -> bool {
self.freeze pub fn get_freeze(&self) -> bool { self.freeze }
}
/// this allows us to re-use the TRNG object /// this allows us to re-use the TRNG object
pub fn trng_u32(&self) -> u32 { pub fn trng_u32(&self) -> u32 { self.trng.get_u32().unwrap() }
self.trng.get_u32().unwrap()
}
pub fn resolve(&mut self, name: &str) -> Result<HashMap<IpAddr, u32>, DnsResponseCode> { pub fn resolve(&mut self, name: &str) -> Result<HashMap<IpAddr, u32>, DnsResponseCode> {
if let Some(dns_address) = self.mgr.get_random() { if let Some(dns_address) = self.mgr.get_random() {
let dns_port = 53; let dns_port = 53;
@ -366,9 +342,7 @@ impl Resolver {
let qclass = QueryClass::IN; let qclass = QueryClass::IN;
let query = Message::query(qname, qtype, qclass, self.trng.get_u32().unwrap() as u16); let query = Message::query(qname, qtype, qclass, self.trng.get_u32().unwrap() as u16);
self.socket self.socket.send_to(&query.datagram, &server).map_err(|_| DnsResponseCode::NetworkError)?;
.send_to(&query.datagram, &server)
.map_err(|_| DnsResponseCode::NetworkError)?;
match self.socket.recv(&mut self.buf) { match self.socket.recv(&mut self.buf) {
Ok(len) => { Ok(len) => {
@ -407,10 +381,7 @@ enum NameConversionError {
} }
fn name_from_msg(env: &xous::MessageEnvelope) -> Result<&str, NameConversionError> { fn name_from_msg(env: &xous::MessageEnvelope) -> Result<&str, NameConversionError> {
let msg = env let msg = env.body.memory_message().ok_or(NameConversionError::InvalidMessageType)?;
.body
.memory_message()
.ok_or(NameConversionError::InvalidMessageType)?;
let valid_bytes = msg.valid.map(|v| v.get()).unwrap_or_else(|| msg.buf.len()); let valid_bytes = msg.valid.map(|v| v.get()).unwrap_or_else(|| msg.buf.len());
if valid_bytes > DNS_NAME_LENGTH_LIMIT || valid_bytes < 1 { if valid_bytes > DNS_NAME_LENGTH_LIMIT || valid_bytes < 1 {
log::error!("valid bytes exceeded DNS name limit"); log::error!("valid bytes exceeded DNS name limit");
@ -418,8 +389,7 @@ fn name_from_msg(env: &xous::MessageEnvelope) -> Result<&str, NameConversionErro
} }
// Safe because we've already validated that it's a valid range // Safe because we've already validated that it's a valid range
let str_slice = unsafe { core::slice::from_raw_parts(msg.buf.as_ptr(), valid_bytes) }; let str_slice = unsafe { core::slice::from_raw_parts(msg.buf.as_ptr(), valid_bytes) };
let name_string = let name_string = core::str::from_utf8(str_slice).map_err(|_| NameConversionError::InvalidString)?;
core::str::from_utf8(str_slice).map_err(|_| NameConversionError::InvalidString)?;
Ok(name_string) Ok(name_string)
} }
@ -494,9 +464,7 @@ fn main() -> ! {
time::start_time_ux(); time::start_time_ux();
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
let dns_sid = xns let dns_sid = xns.register_name(api::SERVER_NAME_DNS, None).expect("can't register server");
.register_name(api::SERVER_NAME_DNS, None)
.expect("can't register server");
log::trace!("registered with NS -- {:?}", dns_sid); log::trace!("registered with NS -- {:?}", dns_sid);
// this will magically populate a list of DNS servers when they become available // this will magically populate a list of DNS servers when they become available
@ -572,12 +540,9 @@ fn main() -> ! {
}; };
} }
Some(Opcode::Lookup) => { Some(Opcode::Lookup) => {
let mut buf = unsafe { let mut buf =
Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) unsafe { Buffer::from_memory_message_mut(msg.body.memory_message_mut().unwrap()) };
}; let name = buf.to_original::<String<DNS_NAME_LENGTH_LIMIT>, _>().unwrap();
let name = buf
.to_original::<String<DNS_NAME_LENGTH_LIMIT>, _>()
.unwrap();
let name_std = std::string::String::from(name.as_str().unwrap()); let name_std = std::string::String::from(name.as_str().unwrap());
if let Some(cache_entry) = dns_cache.get(&name_std) { if let Some(cache_entry) = dns_cache.get(&name_std) {
// pick a random entry // pick a random entry
@ -617,30 +582,20 @@ fn main() -> ! {
} }
} else { } else {
// no names found // no names found
let response = DnsResponse { let response = DnsResponse { addr: None, code: DnsResponseCode::NameError };
addr: None,
code: DnsResponseCode::NameError,
};
buf.replace(response).unwrap(); buf.replace(response).unwrap();
} }
} }
Err(e) => { Err(e) => {
log::debug!("DNS query failed: {}->{:?}", name, e); log::debug!("DNS query failed: {}->{:?}", name, e);
let response = DnsResponse { let response = DnsResponse { addr: None, code: e };
addr: None,
code: e,
};
buf.replace(response).unwrap(); buf.replace(response).unwrap();
} }
} }
} }
} }
Some(Opcode::UpdateTtl) => msg_scalar_unpack!(msg, incr_secs, _, _, _, { Some(Opcode::UpdateTtl) => msg_scalar_unpack!(msg, incr_secs, _, _, _, {
let increment = if incr_secs < u32::MAX as usize { let increment = if incr_secs < u32::MAX as usize { incr_secs as u32 } else { u32::MAX };
incr_secs as u32
} else {
u32::MAX
};
if !resolver.get_freeze() { if !resolver.get_freeze() {
let mut expired_names = Vec::<std::string::String>::new(); let mut expired_names = Vec::<std::string::String>::new();
for (name, cache_map) in dns_cache.iter_mut() { for (name, cache_map) in dns_cache.iter_mut() {

View file

@ -1,3 +1,7 @@
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::num::ParseIntError;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
/// The `time_server` is unique is that it is written for exclusive use by `libstd` to extract time. /// The `time_server` is unique is that it is written for exclusive use by `libstd` to extract time.
/// ///
/// It also has a single hook that is callable from the PDDB to initialize a time value once the /// It also has a single hook that is callable from the PDDB to initialize a time value once the
@ -22,21 +26,18 @@
/// read RTC, plus you get milliseconds resolution. Time "T" can be updated at any time by just /// read RTC, plus you get milliseconds resolution. Time "T" can be updated at any time by just
/// reading the RTC and noting the ticktimer offset at the point of reading. /// reading the RTC and noting the ticktimer offset at the point of reading.
use std::thread; use std::thread;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering}; use chrono::prelude::*;
use gam::modal::*;
#[cfg(any(feature = "precursor", feature = "renode"))] #[cfg(any(feature = "precursor", feature = "renode"))]
use llio::*; use llio::*;
use pddb::PddbMountPoller;
use num_traits::*;
// imports for time ux // imports for time ux
use locales::t; use locales::t;
use chrono::prelude::*; use num_traits::*;
use xous::{Message, send_message}; use pddb::PddbMountPoller;
use gam::modal::*;
// ntp imports // ntp imports
use sntpc::{Error, NtpContext, NtpTimestampGenerator, NtpUdpSocket, Result}; use sntpc::{Error, NtpContext, NtpTimestampGenerator, NtpUdpSocket, Result};
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket}; use xous::{send_message, Message};
use std::num::ParseIntError;
/// This is a "well known name" used by `libstd` to connect to the time server /// This is a "well known name" used by `libstd` to connect to the time server
/// Anyone who wants to check if time has been initialized would use this name. /// Anyone who wants to check if time has been initialized would use this name.
@ -97,30 +98,20 @@ struct StdTimestampGen {
} }
impl NtpTimestampGenerator for StdTimestampGen { impl NtpTimestampGenerator for StdTimestampGen {
fn init(&mut self) { fn init(&mut self) {
self.duration = std::time::SystemTime::now() self.duration =
.duration_since(std::time::SystemTime::UNIX_EPOCH) std::time::SystemTime::now().duration_since(std::time::SystemTime::UNIX_EPOCH).unwrap();
.unwrap();
} }
fn timestamp_sec(&self) -> u64 { fn timestamp_sec(&self) -> u64 { self.duration.as_secs() }
self.duration.as_secs()
}
fn timestamp_subsec_micros(&self) -> u32 { fn timestamp_subsec_micros(&self) -> u32 { self.duration.subsec_micros() }
self.duration.subsec_micros()
} }
}
#[derive(Debug)] #[derive(Debug)]
struct UdpSocketWrapper(UdpSocket); struct UdpSocketWrapper(UdpSocket);
impl NtpUdpSocket for UdpSocketWrapper { impl NtpUdpSocket for UdpSocketWrapper {
fn send_to<T: ToSocketAddrs>( fn send_to<T: ToSocketAddrs>(&self, buf: &[u8], addr: T) -> Result<usize> {
&self,
buf: &[u8],
addr: T,
) -> Result<usize> {
match self.0.send_to(buf, addr) { match self.0.send_to(buf, addr) {
Ok(usize) => Ok(usize), Ok(usize) => Ok(usize),
Err(_) => Err(Error::Network), Err(_) => Err(Error::Network),
@ -180,8 +171,8 @@ pub fn start_time_server() {
let rtc_checked = Arc::new(AtomicBool::new(false)); let rtc_checked = Arc::new(AtomicBool::new(false));
// the public SID is well known and accessible by anyone who uses `libstd` // the public SID is well known and accessible by anyone who uses `libstd`
let pub_sid = xous::create_server_with_address(&TIME_SERVER_PUBLIC) let pub_sid =
.expect("Couldn't create Ticktimer server"); xous::create_server_with_address(&TIME_SERVER_PUBLIC).expect("Couldn't create Ticktimer server");
let self_cid = xous::connect(pub_sid).unwrap(); let self_cid = xous::connect(pub_sid).unwrap();
// this thread handles more sensitive operations on the RTC. // this thread handles more sensitive operations on the RTC.
@ -205,8 +196,9 @@ pub fn start_time_server() {
Some(susres::SuspendOrder::Early), Some(susres::SuspendOrder::Early),
&xns, &xns,
PrivTimeOp::SusRes as u32, PrivTimeOp::SusRes as u32,
priv_conn priv_conn,
).expect("couldn't create suspend/resume object"); )
.expect("couldn't create suspend/resume object");
// on boot, do the validation checks of the RTC. If it is not initialized or corrupted, fix it. // on boot, do the validation checks of the RTC. If it is not initialized or corrupted, fix it.
let mut settings = [0u8; 8]; let mut settings = [0u8; 8];
@ -215,13 +207,13 @@ pub fn start_time_server() {
match i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &mut settings) { match i2c.i2c_read_no_repeated_start(ABRTCMC_I2C_ADR, ABRTCMC_CONTROL3, &mut settings) {
Ok(I2cStatus::ResponseReadOk) => { Ok(I2cStatus::ResponseReadOk) => {
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
break break;
}, }
_ => { _ => {
i2c.i2c_mutex_release(); i2c.i2c_mutex_release();
log::error!("Couldn't check RTC, retrying!"); log::error!("Couldn't check RTC, retrying!");
xous::yield_slice(); // recheck in a fast loop, we really should be able to grab this resource on boot. xous::yield_slice(); // recheck in a fast loop, we really should be able to grab this resource on boot.
}, }
}; };
} }
if is_rtc_invalid(&settings) { if is_rtc_invalid(&settings) {
@ -239,11 +231,14 @@ pub fn start_time_server() {
}), }),
Some(PrivTimeOp::SusRes) => xous::msg_scalar_unpack!(msg, token, _, _, _, { Some(PrivTimeOp::SusRes) => xous::msg_scalar_unpack!(msg, token, _, _, _, {
susres.suspend_until_resume(token).expect("couldn't execute suspend/resume"); susres.suspend_until_resume(token).expect("couldn't execute suspend/resume");
// resync time on resume, but give a little time for other processes to clear as this is not urgent // resync time on resume, but give a little time for other processes to clear as this
// is not urgent
tt.sleep_ms(180).unwrap(); tt.sleep_ms(180).unwrap();
send_message(self_cid, send_message(
Message::new_scalar(TimeOp::HwSync.to_usize().unwrap(), 0, 0, 0, 0) self_cid,
).expect("couldn't queue sync request"); Message::new_scalar(TimeOp::HwSync.to_usize().unwrap(), 0, 0, 0, 0),
)
.expect("couldn't queue sync request");
}), }),
_ => log::error!("Time server private thread received unknown opcode: {:?}", msg), _ => log::error!("Time server private thread received unknown opcode: {:?}", msg),
} }
@ -266,7 +261,8 @@ pub fn start_time_server() {
tt.sleep_ms(42).unwrap(); tt.sleep_ms(42).unwrap();
} }
let mut start_rtc_secs: u64; let mut start_rtc_secs: u64;
// this loop allows us to fail slightly more gracefully in the case that there is an RTC hardware failure // this loop allows us to fail slightly more gracefully in the case that there is an RTC hardware
// failure
loop { loop {
match llio.get_rtc_secs() { match llio.get_rtc_secs() {
Ok(s) => { Ok(s) => {
@ -287,9 +283,11 @@ pub fn start_time_server() {
let pddb_poller = PddbMountPoller::new(); let pddb_poller = PddbMountPoller::new();
// enqueue a the first mount poll message // enqueue a the first mount poll message
#[cfg(not(feature = "minimal-testing"))] #[cfg(not(feature = "minimal-testing"))]
xous::send_message(self_cid, xous::send_message(
xous::Message::new_scalar(TimeOp::PddbMountPoll.to_usize().unwrap(), 0, 0, 0, 0) self_cid,
).expect("couldn't check mount poll"); 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. // an initial behavior which just retuns the raw RTC time, until the PDDB is mounted.
let mut temp = 0; let mut temp = 0;
loop { loop {
@ -308,35 +306,37 @@ pub fn start_time_server() {
log::trace!("mount poll"); log::trace!("mount poll");
} }
temp += 1; temp += 1;
xous::send_message(self_cid, xous::send_message(
xous::Message::new_scalar(TimeOp::PddbMountPoll.to_usize().unwrap(), 0, 0, 0, 0) self_cid,
).expect("couldn't check mount poll"); xous::Message::new_scalar(TimeOp::PddbMountPoll.to_usize().unwrap(), 0, 0, 0, 0),
)
.expect("couldn't check mount poll");
} }
Some(TimeOp::HwSync) => { Some(TimeOp::HwSync) => {
start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value"); start_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
start_tt_ms = tt.elapsed_ms(); start_tt_ms = tt.elapsed_ms();
}, }
Some(TimeOp::GetUtcTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(TimeOp::GetUtcTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let t = let t = start_rtc_secs as i64 * 1000i64 + (tt.elapsed_ms() - start_tt_ms) as i64;
start_rtc_secs as i64 * 1000i64
+ (tt.elapsed_ms() - start_tt_ms) as i64;
log::debug!("hw only UTC ms {}", t); log::debug!("hw only UTC ms {}", t);
// NOTE: endian swap for compatibility with `std` // NOTE: endian swap for compatibility with `std`
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
(t as u64 & 0xFFFF_FFFF) as usize, (t as u64 & 0xFFFF_FFFF) as usize,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize, (((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetUtcTimeMs"); )
.expect("couldn't respond to GetUtcTimeMs");
}), }),
Some(TimeOp::GetLocalTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(TimeOp::GetLocalTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let t = let t = start_rtc_secs as i64 * 1000i64 + (tt.elapsed_ms() - start_tt_ms) as i64;
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"); assert!(t > 0, "time result is negative, this is an error");
log::debug!("hw only local ms {}", t); log::debug!("hw only local ms {}", t);
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize, (((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize, (t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetLocalTimeMs"); )
.expect("couldn't respond to GetLocalTimeMs");
}), }),
Some(TimeOp::WallClockTimeInit) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(TimeOp::WallClockTimeInit) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
// definitely not initialized // definitely not initialized
@ -351,10 +351,13 @@ pub fn start_time_server() {
0 0
}); });
#[cfg(not(feature = "minimal-testing"))] #[cfg(not(feature = "minimal-testing"))]
let mut tz_offset_ms = prefs.timezone_offset().unwrap_or_else(|error| { let mut tz_offset_ms = prefs
.timezone_offset()
.unwrap_or_else(|error| {
log::error!("cannot read timezone offset: {:?}", error); log::error!("cannot read timezone offset: {:?}", error);
None None
}).unwrap_or_default(); })
.unwrap_or_default();
#[cfg(feature = "minimal-testing")] #[cfg(feature = "minimal-testing")]
let mut utc_offset_ms = 0; let mut utc_offset_ms = 0;
#[cfg(feature = "minimal-testing")] #[cfg(feature = "minimal-testing")]
@ -372,9 +375,8 @@ pub fn start_time_server() {
Some(TimeOp::PddbMountPoll) => { Some(TimeOp::PddbMountPoll) => {
// do nothing, we're mounted now. // do nothing, we're mounted now.
continue; continue;
}, }
Some(TimeOp::HwSync) => { Some(TimeOp::HwSync) => match llio.get_rtc_secs() {
match llio.get_rtc_secs() {
Ok(val) => { Ok(val) => {
start_rtc_secs = val; start_rtc_secs = val;
start_tt_ms = tt.elapsed_ms(); start_tt_ms = tt.elapsed_ms();
@ -382,71 +384,82 @@ pub fn start_time_server() {
Err(e) => { Err(e) => {
log::warn!("Error syncing time: {:?}; retrying!", e); log::warn!("Error syncing time: {:?}; retrying!", e);
tt.sleep_ms(82).unwrap(); tt.sleep_ms(82).unwrap();
send_message(self_cid, send_message(
Message::new_scalar(TimeOp::HwSync.to_usize().unwrap(), 0, 0, 0, 0) self_cid,
).expect("couldn't queue sync request"); Message::new_scalar(TimeOp::HwSync.to_usize().unwrap(), 0, 0, 0, 0),
} )
.expect("couldn't queue sync request");
} }
}, },
Some(TimeOp::GetUtcTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { Some(TimeOp::GetUtcTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, {
let t = let t = start_rtc_secs as i64 * 1000i64
start_rtc_secs as i64 * 1000i64
+ (tt.elapsed_ms() - start_tt_ms) as i64 + (tt.elapsed_ms() - start_tt_ms) as i64
+ utc_offset_ms; + utc_offset_ms;
if t < 0 { // the offset has some error in it, perhaps due to an RTC reset. reset the offset! if t < 0 {
log::warn!("Time was negative, recovering from time setting error by clearing utc offset to 0"); // the offset has some error in it, perhaps due to an RTC reset. reset the offset!
log::warn!(
"Time was negative, recovering from time setting error by clearing utc offset to 0"
);
prefs.set_utc_offset(0).ok(); prefs.set_utc_offset(0).ok();
utc_offset_ms = 0; utc_offset_ms = 0;
} }
log::trace!("utc ms {}", t); log::trace!("utc ms {}", t);
// NOTE: endian swap for compatibility with `std` // NOTE: endian swap for compatibility with `std`
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
(t as u64 & 0xFFFF_FFFF) as usize, (t as u64 & 0xFFFF_FFFF) as usize,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize, (((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetUtcTimeMs"); )
.expect("couldn't respond to GetUtcTimeMs");
}), }),
Some(TimeOp::GetLocalTimeMs) => xous::msg_blocking_scalar_unpack!(msg, _, _, _, _, { 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); log::trace!(
let t = "current offset {}",
start_rtc_secs as i64 * 1000i64 (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 + (tt.elapsed_ms() - start_tt_ms) as i64
+ utc_offset_ms + utc_offset_ms
+ tz_offset_ms; + tz_offset_ms;
if t < 0 { if t < 0 {
log::warn!("Time was negative, recovering from time setting error by clearing utc and timezone offsets to 0."); log::warn!(
"Time was negative, recovering from time setting error by clearing utc and timezone offsets to 0."
);
prefs.set_utc_offset(0).ok(); prefs.set_utc_offset(0).ok();
prefs.set_timezone_offset(0).ok(); prefs.set_timezone_offset(0).ok();
utc_offset_ms = 0; utc_offset_ms = 0;
tz_offset_ms = 0; tz_offset_ms = 0;
} }
log::trace!("local since epoch {}", t / 1000); log::trace!("local since epoch {}", t / 1000);
xous::return_scalar2(msg.sender, xous::return_scalar2(
msg.sender,
(((t as u64) >> 32) & 0xFFFF_FFFF) as usize, (((t as u64) >> 32) & 0xFFFF_FFFF) as usize,
(t as u64 & 0xFFFF_FFFF) as usize, (t as u64 & 0xFFFF_FFFF) as usize,
).expect("couldn't respond to GetLocalTimeMs"); )
.expect("couldn't respond to GetLocalTimeMs");
}), }),
Some(TimeOp::SetUtcTimeMs) => xous::msg_scalar_unpack!(msg, utc_hi_ms, utc_lo_ms, _, _, { 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); 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_rtc_secs = llio.get_rtc_secs().expect("couldn't read RTC offset value");
start_tt_ms = tt.elapsed_ms(); start_tt_ms = tt.elapsed_ms();
log::info!("utc_time: {}", utc_time_ms / 1000); log::info!("utc_time: {}", utc_time_ms / 1000);
log::info!("rtc_secs: {}", start_rtc_secs); log::info!("rtc_secs: {}", start_rtc_secs);
log::info!("start_tt_ms: {}", start_tt_ms); log::info!("start_tt_ms: {}", start_tt_ms);
let offset = let offset = utc_time_ms - (start_rtc_secs as i64) * 1000;
utc_time_ms -
(start_rtc_secs as i64) * 1000;
utc_offset_ms = offset; utc_offset_ms = offset;
#[cfg(not(feature = "minimal-testing"))] #[cfg(not(feature = "minimal-testing"))]
prefs.set_utc_offset(offset).unwrap_or_else(|err| { prefs.set_utc_offset(offset).unwrap_or_else(|err| {
log::error!("cannot set utc offset: {:?}", err); log::error!("cannot set utc offset: {:?}", err);
}); });
}), })
}
Some(TimeOp::SetTzOffsetMs) => xous::msg_scalar_unpack!(msg, tz_hi_ms, tz_lo_ms, _, _, { Some(TimeOp::SetTzOffsetMs) => xous::msg_scalar_unpack!(msg, tz_hi_ms, tz_lo_ms, _, _, {
let tz_ms = ((tz_hi_ms as i64) << 32) | (tz_lo_ms as i64); let tz_ms = ((tz_hi_ms as i64) << 32) | (tz_lo_ms as i64);
// sanity check with very broad bounds: I don't know of any time zones that are more than +/2 days from UTC // sanity check with very broad bounds: I don't know of any time zones that are more
// 86400 seconds in a day, times 1000 milliseconds, times 2 days // than +/2 days from UTC 86400 seconds in a day, times 1000
if tz_ms < -(86400 * 1000 * 2) || // milliseconds, times 2 days
tz_ms > 86400 * 1000 * 2 { if tz_ms < -(86400 * 1000 * 2) || tz_ms > 86400 * 1000 * 2 {
log::warn!("Requested timezone offset {} is out of bounds, ignoring!", tz_ms); log::warn!("Requested timezone offset {} is out of bounds, ignoring!", tz_ms);
continue; continue;
} else { } else {
@ -505,9 +518,7 @@ fn is_rtc_invalid(settings: &[u8]) -> bool {
} }
#[allow(dead_code)] #[allow(dead_code)]
fn to_binary(bcd: u8) -> u8 { fn to_binary(bcd: u8) -> u8 { (bcd & 0xf) + ((bcd >> 4) * 10) }
(bcd & 0xf) + ((bcd >> 4) * 10)
}
#[allow(dead_code)] #[allow(dead_code)]
fn to_bcd(binary: u8) -> u8 { fn to_bcd(binary: u8) -> u8 {
let mut lsd: u8 = binary % 10; let mut lsd: u8 = binary % 10;
@ -542,7 +553,7 @@ fn simple_kilofloat_parse(input: &str) -> core::result::Result<i32, ParseIntErro
} }
significance /= 10; significance /= 10;
} else { } else {
return "z".parse::<i32>() // you can't create a ParseIntError any other way return "z".parse::<i32>(); // you can't create a ParseIntError any other way
} }
} }
Ok(result) Ok(result)
@ -559,7 +570,8 @@ pub (crate) fn start_time_ux() {
let xns = xous_names::XousNames::new().unwrap(); let xns = xous_names::XousNames::new().unwrap();
let sid = xns.register_name(crate::TIME_UX_NAME, Some(1)).unwrap(); let sid = xns.register_name(crate::TIME_UX_NAME, Some(1)).unwrap();
let modals = modals::Modals::new(&xns).unwrap(); let modals = modals::Modals::new(&xns).unwrap();
let timeserver_cid = xous::connect(xous::SID::from_bytes(crate::time::TIME_SERVER_PUBLIC).unwrap()).unwrap(); let timeserver_cid =
xous::connect(xous::SID::from_bytes(crate::time::TIME_SERVER_PUBLIC).unwrap()).unwrap();
let pddb_poller = pddb::PddbMountPoller::new(); let pddb_poller = pddb::PddbMountPoller::new();
let trng = trng::Trng::new(&xns).unwrap(); let trng = trng::Trng::new(&xns).unwrap();
@ -570,7 +582,9 @@ pub (crate) fn start_time_ux() {
match FromPrimitive::from_usize(msg.body.id()) { match FromPrimitive::from_usize(msg.body.id()) {
Some(crate::TimeUxOp::SetTime) => xous::msg_scalar_unpack!(msg, _, _, _, _, { Some(crate::TimeUxOp::SetTime) => xous::msg_scalar_unpack!(msg, _, _, _, _, {
if !pddb_poller.is_mounted_nonblocking() { if !pddb_poller.is_mounted_nonblocking() {
modals.show_notification(t!("stats.please_mount", locales::LANG), None).expect("couldn't show notification"); modals
.show_notification(t!("stats.please_mount", locales::LANG), None)
.expect("couldn't show notification");
continue; continue;
} }
let mut tz_set = false; let mut tz_set = false;
@ -579,7 +593,7 @@ pub (crate) fn start_time_ux() {
Some(data) => { Some(data) => {
tz_set = true; tz_set = true;
data data
}, }
None => { None => {
tz_set = false; tz_set = false;
0i64 0i64
@ -595,40 +609,52 @@ pub (crate) fn start_time_ux() {
// a key exists, but nothing was written to it (length of key was 0 or inappropriate) // a key exists, but nothing was written to it (length of key was 0 or inappropriate)
if !tz_set { if !tz_set {
log::info!("{}RTC.TZ,{}", xous::BOOKEND_START, xous::BOOKEND_END); log::info!("{}RTC.TZ,{}", xous::BOOKEND_START, xous::BOOKEND_END);
let tz_str = modals.alert_builder(t!("rtc.timezone", locales::LANG)) let tz_str = modals
.alert_builder(t!("rtc.timezone", locales::LANG))
.field(None, Some(tz_ux_validator)) .field(None, Some(tz_ux_validator))
.build() .build()
.expect("couldn't get timezone") .expect("couldn't get timezone")
.first(); .first();
let tz = simple_kilofloat_parse(tz_str.as_str()).expect("pre-validated input failed to re-parse!"); let tz = simple_kilofloat_parse(tz_str.as_str())
.expect("pre-validated input failed to re-parse!");
log::info!("got tz offset {}", tz); log::info!("got tz offset {}", tz);
tz_offset_ms = (tz * 3600) as i64; tz_offset_ms = (tz * 3600) as i64;
xous::send_message(timeserver_cid, xous::send_message(
timeserver_cid,
Message::new_scalar( Message::new_scalar(
crate::time::TimeOp::SetTzOffsetMs.to_usize().unwrap(), crate::time::TimeOp::SetTzOffsetMs.to_usize().unwrap(),
(tz_offset_ms >> 32) as usize, (tz_offset_ms >> 32) as usize,
(tz_offset_ms & 0xFFFF_FFFF) as usize, (tz_offset_ms & 0xFFFF_FFFF) as usize,
0, 0, 0,
0,
),
) )
).expect("couldn't set timezone"); .expect("couldn't set timezone");
} }
// see if we want to try to use NTP or not // see if we want to try to use NTP or not
log::info!("{}RTC.NTP,{}", xous::BOOKEND_START, xous::BOOKEND_END); log::info!("{}RTC.NTP,{}", xous::BOOKEND_START, xous::BOOKEND_END);
modals.add_list_item(t!("pddb.yes", locales::LANG)).expect("couldn't build radio item list"); modals
modals.add_list_item(t!("pddb.no", locales::LANG)).expect("couldn't build radio item list"); .add_list_item(t!("pddb.yes", locales::LANG))
.expect("couldn't build radio item list");
modals
.add_list_item(t!("pddb.no", locales::LANG))
.expect("couldn't build radio item list");
let mut try_ntp = true; let mut try_ntp = true;
match modals.get_radiobutton(t!("rtc.try_ntp", locales::LANG)) { match modals.get_radiobutton(t!("rtc.try_ntp", locales::LANG)) {
Ok(selection) => { Ok(selection) => {
if selection == t!("pddb.no", locales::LANG) { if selection == t!("pddb.no", locales::LANG) {
try_ntp = false; try_ntp = false;
} }
}, }
_ => log::error!("get_radiobutton failed"), _ => log::error!("get_radiobutton failed"),
} }
if try_ntp { if try_ntp {
let local_port = (trng.get_u32().unwrap() % 16384 + 49152) as u16; let local_port = (trng.get_u32().unwrap() % 16384 + 49152) as u16;
let socket_addr = SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)), local_port); let socket_addr = SocketAddr::new(
std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)),
local_port,
);
let socket = UdpSocket::bind(socket_addr).expect("Unable to create UDP socket"); let socket = UdpSocket::bind(socket_addr).expect("Unable to create UDP socket");
log::debug!("NTP rx socket created {:?}", socket); log::debug!("NTP rx socket created {:?}", socket);
socket socket
@ -640,24 +666,30 @@ pub (crate) fn start_time_ux() {
match result { match result {
Ok(time) => { Ok(time) => {
log::info!("Got NTP time: {}.{}", time.sec(), time.sec_fraction()); log::info!("Got NTP time: {}.{}", time.sec(), time.sec_fraction());
let current_time = Utc.ymd(1970, 1, 1).and_hms(0, 0, 0) + chrono::Duration::seconds(time.sec() as i64); let current_time = Utc.ymd(1970, 1, 1).and_hms(0, 0, 0)
+ chrono::Duration::seconds(time.sec() as i64);
log::info!("Setting UTC time: {:?}", current_time.to_string()); log::info!("Setting UTC time: {:?}", current_time.to_string());
xous::send_message(timeserver_cid, xous::send_message(
timeserver_cid,
Message::new_scalar( Message::new_scalar(
crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(), crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(),
((current_time.timestamp_millis() as u64) >> 32) as usize, ((current_time.timestamp_millis() as u64) >> 32) as usize,
(current_time.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize, (current_time.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize,
0, 0, 0,
0,
),
) )
).expect("couldn't set time"); .expect("couldn't set time");
log::info!("{}RTC.NTPOK,{}", xous::BOOKEND_START, xous::BOOKEND_END); log::info!("{}RTC.NTPOK,{}", xous::BOOKEND_START, xous::BOOKEND_END);
continue; continue;
} }
Err(err) => { Err(err) => {
log::info!("Err: {:?}", err); log::info!("Err: {:?}", err);
log::info!("{}RTC.NTPFAIL,{}", xous::BOOKEND_START, xous::BOOKEND_END); log::info!("{}RTC.NTPFAIL,{}", xous::BOOKEND_START, xous::BOOKEND_END);
modals.show_notification(t!("rtc.ntp_fail", locales::LANG), None).expect("couldn't show NTP error"); modals
}, .show_notification(t!("rtc.ntp_fail", locales::LANG), None)
.expect("couldn't show NTP error");
}
} }
} }
@ -668,18 +700,38 @@ pub (crate) fn start_time_ux() {
let mut days: u8 = 0; let mut days: u8 = 0;
let mut years: u8 = 0; let mut years: u8 = 0;
let date = modals.alert_builder(t!("rtc.set_time_modal", locales::LANG)) let date = modals
.field(Some(String::from(t!("rtc.month", locales::LANG))), Some(rtc_ux_validate_month)) .alert_builder(t!("rtc.set_time_modal", locales::LANG))
.field(Some(String::from(t!("rtc.day", locales::LANG))), Some(rtc_ux_validate_day)) .field(
.field(Some(String::from(t!("rtc.year", locales::LANG))), Some(rtc_ux_validate_year)) Some(String::from(t!("rtc.month", locales::LANG))),
.field(Some(String::from(t!("rtc.hour", locales::LANG))), Some(rtc_ux_validate_hour)) Some(rtc_ux_validate_month),
.field(Some(String::from(t!("rtc.minute", locales::LANG))), Some(rtc_ux_validate_minute)) )
.field(Some(String::from(t!("rtc.seconds", locales::LANG))), Some(rtc_ux_validate_seconds)) .field(
Some(String::from(t!("rtc.day", locales::LANG))),
Some(rtc_ux_validate_day),
)
.field(
Some(String::from(t!("rtc.year", locales::LANG))),
Some(rtc_ux_validate_year),
)
.field(
Some(String::from(t!("rtc.hour", locales::LANG))),
Some(rtc_ux_validate_hour),
)
.field(
Some(String::from(t!("rtc.minute", locales::LANG))),
Some(rtc_ux_validate_minute),
)
.field(
Some(String::from(t!("rtc.seconds", locales::LANG))),
Some(rtc_ux_validate_seconds),
)
.build() .build()
.expect("cannot get date from user"); .expect("cannot get date from user");
for (index, elem) in date.content().iter().enumerate() { for (index, elem) in date.content().iter().enumerate() {
let elem = elem.as_str().parse::<u8>().expect("pre-validated input failed to re-parse!"); let elem =
elem.as_str().parse::<u8>().expect("pre-validated input failed to re-parse!");
match index { match index {
0 => months = elem, 0 => months = elem,
1 => days = elem, 1 => days = elem,
@ -687,29 +739,36 @@ pub (crate) fn start_time_ux() {
3 => hours = elem, 3 => hours = elem,
4 => mins = elem, 4 => mins = elem,
5 => secs = elem, 5 => secs = elem,
_ => {}, _ => {}
} }
} }
log::info!("Setting time: {}/{}/{} {}:{}:{}", months, days, years, hours, mins, secs); log::info!("Setting time: {}/{}/{} {}:{}:{}", months, days, years, hours, mins, secs);
let new_dt = chrono::FixedOffset::east((tz_offset_ms / 1000) as i32).ymd(years as i32 + 2000, months as u32, days as u32) let new_dt = chrono::FixedOffset::east((tz_offset_ms / 1000) as i32)
.ymd(years as i32 + 2000, months as u32, days as u32)
.and_hms(hours as u32, mins as u32, secs as u32); .and_hms(hours as u32, mins as u32, secs as u32);
xous::send_message(timeserver_cid, xous::send_message(
timeserver_cid,
Message::new_scalar( Message::new_scalar(
crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(), crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(),
((new_dt.timestamp_millis() as u64) >> 32) as usize, ((new_dt.timestamp_millis() as u64) >> 32) as usize,
(new_dt.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize, (new_dt.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize,
0, 0, 0,
0,
),
) )
).expect("couldn't set time"); .expect("couldn't set time");
}), }),
Some(crate::TimeUxOp::SetTimeZone) => xous::msg_scalar_unpack!(msg, _, _, _, _, { Some(crate::TimeUxOp::SetTimeZone) => xous::msg_scalar_unpack!(msg, _, _, _, _, {
if !pddb_poller.is_mounted_nonblocking() { if !pddb_poller.is_mounted_nonblocking() {
modals.show_notification(t!("stats.please_mount", locales::LANG), None).expect("couldn't show notification"); modals
.show_notification(t!("stats.please_mount", locales::LANG), None)
.expect("couldn't show notification");
continue; continue;
} }
let tz_str = modals.alert_builder(t!("rtc.timezone", locales::LANG)) let tz_str = modals
.alert_builder(t!("rtc.timezone", locales::LANG))
.field(None, Some(tz_ux_validator)) .field(None, Some(tz_ux_validator))
.build() .build()
.expect("couldn't get timezone") .expect("couldn't get timezone")
@ -718,14 +777,17 @@ pub (crate) fn start_time_ux() {
.expect("pre-validated input failed to re-parse!"); .expect("pre-validated input failed to re-parse!");
log::info!("got tz offset {}", tz); log::info!("got tz offset {}", tz);
let tzoff_ms = (tz * 3600) as i64; let tzoff_ms = (tz * 3600) as i64;
xous::send_message(timeserver_cid, xous::send_message(
timeserver_cid,
Message::new_scalar( Message::new_scalar(
crate::time::TimeOp::SetTzOffsetMs.to_usize().unwrap(), crate::time::TimeOp::SetTzOffsetMs.to_usize().unwrap(),
(tzoff_ms >> 32) as usize, (tzoff_ms >> 32) as usize,
(tzoff_ms & 0xFFFF_FFFF) as usize, (tzoff_ms & 0xFFFF_FFFF) as usize,
0, 0, 0,
0,
),
) )
).expect("couldn't set timezone"); .expect("couldn't set timezone");
}), }),
Some(crate::TimeUxOp::Quit) => { Some(crate::TimeUxOp::Quit) => {
xous::return_scalar(msg.sender, 0).unwrap(); xous::return_scalar(msg.sender, 0).unwrap();
@ -756,9 +818,11 @@ fn tz_ux_validator(input: TextEntryPayload) -> Option<ValidatorErr> {
let text_str = input.as_str(); let text_str = input.as_str();
match simple_kilofloat_parse(text_str) { match simple_kilofloat_parse(text_str) {
Ok(input) => if input < -12_000 || input > 14_000 { Ok(input) => {
if input < -12_000 || input > 14_000 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))); return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
}, }
}
_ => return Some(ValidatorErr::from_str(t!("rtc.integer_err", locales::LANG))), _ => return Some(ValidatorErr::from_str(t!("rtc.integer_err", locales::LANG))),
} }
None None
@ -773,7 +837,7 @@ fn rtc_ux_validate_month(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input < 1 || input > 12 { if input < 1 || input > 12 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
@ -788,7 +852,7 @@ fn rtc_ux_validate_day(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input < 1 || input > 31 { if input < 1 || input > 31 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
@ -803,7 +867,7 @@ fn rtc_ux_validate_year(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input > 99 { if input > 99 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
@ -818,7 +882,7 @@ fn rtc_ux_validate_hour(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input > 23 { if input > 23 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
@ -833,7 +897,7 @@ fn rtc_ux_validate_minute(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input > 59 { if input > 59 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
@ -848,9 +912,8 @@ fn rtc_ux_validate_seconds(input: TextEntryPayload) -> Option<ValidatorErr> {
}; };
if input > 59 { if input > 59 {
return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG))) return Some(ValidatorErr::from_str(t!("rtc.range_err", locales::LANG)));
} }
None None
} }