Crates.io | sntpc |
lib.rs | sntpc |
version | |
source | src |
created_at | 2019-02-15 22:14:53.524274 |
updated_at | 2025-01-15 13:13:41.635115 |
description | Library for making SNTP requests |
homepage | https://github.com/vpetrigo/sntpc |
repository | https://github.com/vpetrigo/sntpc |
max_upload_size | |
id | 115042 |
Cargo.toml error: | TOML parse error at line 23, column 1 | 23 | autolib = false | ^^^^^^^ unknown field `autolib`, expected one of `name`, `version`, `edition`, `authors`, `description`, `readme`, `license`, `repository`, `homepage`, `documentation`, `build`, `resolver`, `links`, `default-run`, `default_dash_run`, `rust-version`, `rust_dash_version`, `rust_version`, `license-file`, `license_dash_file`, `license_file`, `licenseFile`, `license_capital_file`, `forced-target`, `forced_dash_target`, `autobins`, `autotests`, `autoexamples`, `autobenches`, `publish`, `metadata`, `keywords`, `categories`, `exclude`, `include` |
size | 0 |
This crate provides a method for sending requests to NTP servers and process responses, extracting received timestamp.
Supported SNTP protocol versions:
More information about this crate can be found in the crate documentation
[dependencies]
sntpc = { version = "0.5", features = ["sync"] }
use sntpc::{sync::get_time, NtpContext, StdTimestampGen};
use std::net::{SocketAddr, ToSocketAddrs, UdpSocket};
use std::thread;
use std::time::Duration;
#[allow(dead_code)]
const POOL_NTP_ADDR: &str = "pool.ntp.org:123";
#[allow(dead_code)]
const GOOGLE_NTP_ADDR: &str = "time.google.com:123";
fn main() {
#[cfg(feature = "log")]
if cfg!(debug_assertions) {
simple_logger::init_with_level(log::Level::Trace).unwrap();
} else {
simple_logger::init_with_level(log::Level::Info).unwrap();
}
let socket =
UdpSocket::bind("0.0.0.0:0").expect("Unable to crate UDP socket");
socket
.set_read_timeout(Some(Duration::from_secs(2)))
.expect("Unable to set UDP socket read timeout");
for addr in POOL_NTP_ADDR.to_socket_addrs().unwrap() {
let ntp_context = NtpContext::new(StdTimestampGen::default());
let result = get_time(addr, &socket, ntp_context);
match result {
Ok(time) => {
assert_ne!(time.sec(), 0);
let seconds = time.sec();
let microseconds = u64::from(time.sec_fraction()) * 1_000_000
/ u64::from(u32::MAX);
println!("Got time from [{POOL_NTP_ADDR}] {addr}: {seconds}.{microseconds}");
break;
}
Err(err) => println!("Err: {err:?}"),
}
thread::sleep(Duration::new(2, 0));
}
}
You can find this example as well as other example projects in the example directory.
no_std
supportThere is an example available on how to use smoltcp
stack and that should provide
general idea on how to bootstrap no_std
networking and timestamping tools for sntpc
library usage
async
supportStarting version 0.5
the default interface is async
. If you want to use synchronous interface, read about sync
feature below.
tokio
example: examples/tokio
There is also no_std
support with feature async
, but it requires Rust >= 1.75-nightly
version.
The example can be found in separate repository.
sync
supportsntpc
crate is async
by default, since most of the frameworks (I have seen) for embedded systems utilize
asynchronous approach, e.g.:
If you need fully synchronous interface it is available in the sntpc::sync
submodule and respective sync
-feature
enabled. In the case someone needs a synchronous socket support the currently async NtpUdpSocket
trait can be
implemented in a fully synchronous manner. This is an example for the std::net::UdpSocket
that is available in the
crate:
#[cfg(feature = "std")]
impl NtpUdpSocket for UdpSocket {
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> Result<usize> {
match self.send_to(buf, addr) {
Ok(usize) => Ok(usize),
Err(_) => Err(Error::Network),
}
}
async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
match self.recv_from(buf) {
Ok((size, addr)) => Ok((size, addr)),
Err(_) => Err(Error::Network),
}
}
}
As you can see, you may implement everything as synchronous, sntpc
synchronous interface handles async
-like stuff
internally.
That approach also allows to avoid issues with maybe_async
when the
sync/async feature violates Cargo requirements:
That is, enabling a feature should not disable functionality, and it should usually be safe to enable any combination of features.
Small overhead introduced by creating an executor should be negligible.
Contributions are always welcome! If you have an idea, it's best to float it by me before working on it to ensure no effort is wasted. If there's already an open issue for it, knock yourself out. See the contributing section for additional details
NtpResult
structureasync
supportREADME.md
calculate_offset
embassy
socket supportdefmt
support and elaborating on embassy
exampleembassy-net
support and adding missing defmt
format support
for some sntpc
typesReally appreciate all your efforts! Please let me know if I forgot someone.