From e759eebd6f3573f7f52ce796de83842dfe29442e Mon Sep 17 00:00:00 2001 From: decentclock Date: Wed, 17 Aug 2022 12:26:47 -0600 Subject: [PATCH] Add sntp, sync the time on startup --- sphinx-key/src/conn/mod.rs | 1 + sphinx-key/src/conn/sntp.rs | 13 +++++++++++++ sphinx-key/src/main.rs | 10 ++++++++++ 3 files changed, 24 insertions(+) create mode 100644 sphinx-key/src/conn/sntp.rs diff --git a/sphinx-key/src/conn/mod.rs b/sphinx-key/src/conn/mod.rs index 0ce7cb3..ae2004c 100644 --- a/sphinx-key/src/conn/mod.rs +++ b/sphinx-key/src/conn/mod.rs @@ -1,6 +1,7 @@ pub mod wifi; pub mod http; pub mod mqtt; +pub mod sntp; mod html; diff --git a/sphinx-key/src/conn/sntp.rs b/sphinx-key/src/conn/sntp.rs new file mode 100644 index 0000000..3f79cf1 --- /dev/null +++ b/sphinx-key/src/conn/sntp.rs @@ -0,0 +1,13 @@ +use esp_idf_svc::sntp::EspSntp; +use esp_idf_svc::sntp::SyncStatus::Completed; +use std::time::Duration; +use std::thread; + +pub fn sync_time() { + let sntp = EspSntp::new_default().unwrap(); + println!("SNTP initialized"); + while sntp.get_sync_status() != Completed { + println!("Waiting for sntp sync..."); + thread::sleep(Duration::from_secs(1)); + } +} diff --git a/sphinx-key/src/main.rs b/sphinx-key/src/main.rs index f88b6c6..5423b52 100644 --- a/sphinx-key/src/main.rs +++ b/sphinx-key/src/main.rs @@ -12,6 +12,7 @@ use esp_idf_sys as _; // If using the `binstart` feature of `esp-idf-sys`, alway use std::sync::{mpsc, Arc}; use std::thread; use std::time::Duration; +use std::time::SystemTime; use embedded_svc::storage::RawStorage; use esp_idf_hal::peripherals::Peripherals; @@ -74,6 +75,15 @@ fn main() -> Result<()> { } }; + conn::sntp::sync_time(); + let now = SystemTime::now() + .duration_since(SystemTime::UNIX_EPOCH) + .unwrap(); + println!( + "Completed the time sync, here is the UNIX time: {}", + now.as_secs(), + ); + led_tx.send(Status::ConnectingToMqtt).unwrap(); // _conn needs to stay in scope or its dropped loop {