add NTP to time setting via SNTP library

This commit is contained in:
bunnie 2022-04-05 04:19:53 +08:00
parent d183009cb6
commit 532c4a4f1f
7 changed files with 131 additions and 4 deletions

17
Cargo.lock generated
View file

@ -1675,6 +1675,12 @@ dependencies = [
"memoffset",
]
[[package]]
name = "no-std-net"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1bcece43b12349917e096cddfa66107277f123e6c96a5aea78711dc601a47152"
[[package]]
name = "nom"
version = "5.1.2"
@ -2589,6 +2595,16 @@ dependencies = [
"managed",
]
[[package]]
name = "sntpc"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4dd9ef0de174c00dfc61054e7402b8b133a03943c2c9697c497650c4d2cf52f3"
dependencies = [
"log",
"no-std-net",
]
[[package]]
name = "spectrum-analyzer"
version = "0.5.2"
@ -2661,6 +2677,7 @@ dependencies = [
"pddb",
"rkyv",
"root-keys",
"sntpc",
"susres",
"ticktimer-server",
"trng",

View file

@ -164,7 +164,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc<AtomicU3
send_message(run_cid, Message::new_scalar(PumpOp::Pump.to_usize().unwrap(), 0, 0, 0, 0)).expect("couldn't kick off next poll");
loop {
let mut msg = xous::receive_message(sid).unwrap();
log::debug!("got msg: {:?}", msg);
log::trace!("got msg: {:?}", msg);
match FromPrimitive::from_usize(msg.body.id()) {
Some(ConnectionManagerOpcode::SuspendResume) => xous::msg_scalar_unpack!(msg, _, _, _, _, {
// this doesn't follow the usual "suspender" pattern. In fact, we don't do anything special on suspend;

View file

@ -1049,6 +1049,7 @@ fn xmain() -> ! {
}
Some(Opcode::StdUdpClose) => {
log::debug!("StdUdpClose");
let pid = msg.sender.pid();
let connection_idx = msg.body.id() >> 16;
let handle = if let Some(connection) = process_sockets
@ -1070,7 +1071,7 @@ fn xmain() -> ! {
sockets.remove(handle);
if let Some(response) = msg.body.memory_message_mut() {
response.buf.as_slice_mut::<u8>()[0] = 0;
} else if !msg.body.is_blocking() && msg.body.is_blocking() {
} else if msg.body.is_blocking() {
xous::return_scalar(msg.sender, 0).ok();
}
}
@ -1560,6 +1561,7 @@ fn xmain() -> ! {
} else {
match socket.recv() {
Ok((data, endpoint)) => {
log::debug!("netpump udp rx");
udp_rx_success(
// unwrap is safe here because the message was type-checked prior to insertion into the waiting queue
msg.body.memory_message_mut().unwrap().buf.as_slice_mut(),

View file

@ -62,7 +62,7 @@ pub(crate) fn std_udp_bind(
let body = msg.body.memory_message_mut().unwrap();
let bfr = body.buf.as_slice_mut::<u8>();
log::trace!("successfully connected: {}", idx);
log::trace!("successfully connected: {} -> {:?}:{}", idx, address, local_port);
bfr[0] = 0;
bfr[1] = idx;
}
@ -126,6 +126,7 @@ pub(crate) fn std_udp_rx(
} else {
match socket.recv() {
Ok((data, endpoint)) => {
log::debug!("immediate udp rx");
udp_rx_success(body.buf.as_slice_mut(), data, endpoint);
}
Err(e) => {
@ -190,7 +191,7 @@ pub(crate) fn std_udp_tx(
};
let len = u16::from_le_bytes([bytes[19], bytes[20]]);
// attempt the tx
log::trace!("udp tx to fd {}", connection_handle_index);
log::debug!("udp tx to fd {} -> {:?}:{} {:?}", connection_handle_index, address, remote_port, &bytes[21..21 + len as usize]);
let mut socket = sockets.get::<UdpSocket>(*handle);
match socket.send_slice(&bytes[21..21 + len as usize], IpEndpoint::new(address, remote_port)) {
Ok(_) => {
@ -205,6 +206,7 @@ pub(crate) fn std_udp_tx(
}
pub(crate) fn udp_rx_success(buf: &mut [u8], rx: &[u8], ep: IpEndpoint) {
log::debug!("udp_rx: {:?} -> {:x?}", ep, rx);
buf[0] = 0;
let rx_len = (rx.len() as u16).to_le_bytes();
buf[1] = rx_len[0];
@ -235,6 +237,7 @@ pub(crate) fn udp_rx_success(buf: &mut [u8], rx: &[u8], ep: IpEndpoint) {
}
pub(crate) fn udp_failure(mut env: xous::MessageEnvelope, code: NetError) -> Option<()> {
log::trace!("udp_failure: {:?}", code);
// If it's not a memory message, don't fill in the return information.
let body = match env.body.memory_message_mut() {
None => {

View file

@ -32,6 +32,7 @@ num-traits = {version = "0.2.14", default-features = false}
rkyv = {version = "0.4.3", default-features = false, features = ["const_generics"]}
chrono = {version = "0.4.19", default-features = false, features = ["std"]}
sntpc = {version = "0.3.1", features = ["log"]}
[target.'cfg(not(any(windows,unix)))'.dependencies]
utralib = {path = "../../utralib"}

View file

@ -168,6 +168,18 @@
"zh": "外壳聊天",
"en-tts": "Shellchat"
},
"rtc.try_ntp": {
"en": "Attempt to automatically set time with NTP?",
"ja": "NTPで時間を設定しようとしますか?",
"zh": "尝试用 NTP 设置时间?",
"en-tts": "Attempt to automatically set time with NTP?"
},
"rtc.ntp_fail": {
"en": "NTP query failed, please enter time manually.",
"ja": "NTPクエリが失敗しました。時間を手動で入力してください。",
"zh": "NTP 查询失败,请手动输入时间。",
"en-tts": "NTP query failed, please enter time manually."
},
"rtc.month": {
"en": "Enter month (1-12)",
"ja": "月(1-12)を入力してください。",

View file

@ -33,6 +33,9 @@ use locales::t;
use chrono::prelude::*;
use xous::Message;
use gam::modal::*;
// ntp imports
use sntpc::{Error, NtpContext, NtpTimestampGenerator, NtpUdpSocket, Result};
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
/// This is a "well known name" used by `libstd` to connect to the time server
/// Even thought it is "public" nobody connects to it directly, they connect to it via `libstd`
@ -96,6 +99,49 @@ pub(crate) enum TimeUxOp {
SetTimeZone,
Quit,
}
#[derive(Copy, Clone, Default)]
struct StdTimestampGen {
duration: std::time::Duration,
}
impl NtpTimestampGenerator for StdTimestampGen {
fn init(&mut self) {
self.duration = std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
.unwrap();
}
fn timestamp_sec(&self) -> u64 {
self.duration.as_secs()
}
fn timestamp_subsec_micros(&self) -> u32 {
self.duration.subsec_micros()
}
}
#[derive(Debug)]
struct UdpSocketWrapper(UdpSocket);
impl NtpUdpSocket for UdpSocketWrapper {
fn send_to<T: ToSocketAddrs>(
&self,
buf: &[u8],
addr: T,
) -> Result<usize> {
match self.0.send_to(buf, addr) {
Ok(usize) => Ok(usize),
Err(_) => Err(Error::Network),
}
}
fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
match self.0.recv_from(buf) {
Ok((size, addr)) => Ok((size, addr)),
Err(_) => Err(Error::Network),
}
}
}
pub fn start_time_server() {
let rtc_checked = Arc::new(AtomicBool::new(false));
@ -440,6 +486,7 @@ pub fn start_time_ux(sid: xous::SID) {
let modals = modals::Modals::new(&xns).unwrap();
let timeserver_cid = xous::connect(xous::SID::from_bytes(crate::time::TIME_SERVER_PUBLIC).unwrap()).unwrap();
let pddb_poller = pddb::PddbMountPoller::new();
let trng = trng::Trng::new(&xns).unwrap();
loop {
let msg = xous::receive_message(sid).unwrap();
@ -486,6 +533,51 @@ pub fn start_time_ux(sid: xous::SID) {
).expect("couldn't set timezone");
}
// see if we want to try to use NTP or not
modals.add_list_item(t!("pddb.yes", xous::LANG)).expect("couldn't build radio item list");
modals.add_list_item(t!("pddb.no", xous::LANG)).expect("couldn't build radio item list");
let mut try_ntp = true;
match modals.get_radiobutton(t!("rtc.try_ntp", xous::LANG)) {
Ok(selection) => {
if selection == t!("pddb.no", xous::LANG) {
try_ntp = false;
}
},
_ => log::error!("get_radiobutton failed"),
}
if try_ntp {
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 = UdpSocket::bind(socket_addr).expect("Unable to create UDP socket");
log::debug!("NTP rx socket created {:?}", socket);
socket
.set_read_timeout(Some(std::time::Duration::from_secs(2)))
.expect("Unable to set UDP socket read timeout");
let sock_wrapper = UdpSocketWrapper(socket);
let ntp_context = NtpContext::new(StdTimestampGen::default());
let result = sntpc::get_time("time.google.com:123", sock_wrapper, ntp_context);
match result {
Ok(time) => {
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);
log::info!("Setting UTC time: {:?}", current_time.to_string());
xous::send_message(timeserver_cid,
Message::new_scalar(
crate::time::TimeOp::SetUtcTimeMs.to_usize().unwrap(),
((current_time.timestamp_millis() as u64) >> 32) as usize,
(current_time.timestamp_millis() as u64 & 0xFFFF_FFFF) as usize,
0, 0,
)
).expect("couldn't set time");
continue;
}
Err(err) => {
log::info!("Err: {:?}", err);
modals.show_notification(t!("rtc.ntp_fail", xous::LANG)).expect("couldn't show NTP error");
},
}
}
let secs: u8;
let mins: u8;
let hours: u8;