From 532c4a4f1ff0dabf71211250e167997afacba26c Mon Sep 17 00:00:00 2001 From: bunnie Date: Tue, 5 Apr 2022 04:19:53 +0800 Subject: [PATCH] add NTP to time setting via SNTP library --- Cargo.lock | 17 +++++ services/net/src/connection_manager.rs | 2 +- services/net/src/main.rs | 4 +- services/net/src/std_udp.rs | 7 +- services/status/Cargo.toml | 1 + services/status/locales/i18n.json | 12 ++++ services/status/src/time.rs | 92 ++++++++++++++++++++++++++ 7 files changed, 131 insertions(+), 4 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index bed8bcbf7..8165ca1ff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -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", diff --git a/services/net/src/connection_manager.rs b/services/net/src/connection_manager.rs index 482aeb6cb..9282264ee 100644 --- a/services/net/src/connection_manager.rs +++ b/services/net/src/connection_manager.rs @@ -164,7 +164,7 @@ pub(crate) fn connection_manager(sid: xous::SID, activity_interval: Arc xous::msg_scalar_unpack!(msg, _, _, _, _, { // this doesn't follow the usual "suspender" pattern. In fact, we don't do anything special on suspend; diff --git a/services/net/src/main.rs b/services/net/src/main.rs index 1fa0d11a6..4ef1b9dae 100644 --- a/services/net/src/main.rs +++ b/services/net/src/main.rs @@ -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::()[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(), diff --git a/services/net/src/std_udp.rs b/services/net/src/std_udp.rs index 7591583e3..f7f7ce854 100644 --- a/services/net/src/std_udp.rs +++ b/services/net/src/std_udp.rs @@ -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::(); - 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::(*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 => { diff --git a/services/status/Cargo.toml b/services/status/Cargo.toml index 4a11c8da8..f24ac67b2 100644 --- a/services/status/Cargo.toml +++ b/services/status/Cargo.toml @@ -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"} diff --git a/services/status/locales/i18n.json b/services/status/locales/i18n.json index 471cc5ac3..20f9e1e10 100644 --- a/services/status/locales/i18n.json +++ b/services/status/locales/i18n.json @@ -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)を入力してください。", diff --git a/services/status/src/time.rs b/services/status/src/time.rs index e8e4cb432..3026dd500 100644 --- a/services/status/src/time.rs +++ b/services/status/src/time.rs @@ -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( + &self, + buf: &[u8], + addr: T, + ) -> Result { + 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;