Expand description
Rust SNTP client
§Overview
This crate provides a method for sending requests to NTP servers and process responses, extracting the received timestamp. Supported SNTP protocol versions:
§Usage
Put this in your Cargo.toml:
[dependencies]
sntpc = "0.7"§Features
sntpc supports several features:
std: includes functionality that depends on the standard librarysync: enables synchronous interfaceutils: includes functionality that mostly OS specific and allows system time synclog: enables library debug output during executiondefmt: enables library debug output using defmtstd-socket: addNtpUdpSockettrait implementation forstd::net::UdpSocketembassy-socket: addNtpUdpSockettrait implementation forembassy_net::udp::UdpSockettokio-socket: addNtpUdpSockettrait implementation fortokio::net::UdpSocket
Warning: log and defmt are mutually exclusive features. If for some reason both are
enabled, defmt is considered to have a higher priority feature, so all logging
will use defmt API.
Warning: utils feature is not stable and may change in the future.
§Details
There are multiple approaches to how the library can be used:
- under environments where networking stuff is hidden in system/RTOS kernel,
get_timecan be used since it encapsulates network I/O - under environments where TCP/IP stack requires calling some helper functions like
poll,wait, etc. and/or there are no options to perform I/O operations within a single call,sntp_send_requestandsntp_process_responsecan be used
As sntpc supports no_std environment as well, it was
decided to provide a set of traits to implement for a network object (UdpSocket)
and timestamp generator:
NtpUdpSockettrait should be implemented forUdpSocket-like objects for the library to be able to send and receive data from NTP serversNtpTimestampGeneratortrait should be implemented for timestamp generator objects to provide the library with system-related timestamps
§Logging support
Library debug logs can be enabled in executables by enabling the log or defmt
feature. Server addresses, response payload will be printed.
§Example
use sntpc::{get_time, NtpContext, NtpUdpSocket, NtpTimestampGenerator, Result};
use std::net::{SocketAddr, ToSocketAddrs};
use core::net::{IpAddr, Ipv4Addr};
use std::net::UdpSocket;
#[derive(Copy, Clone)]
struct Timestamp;
impl NtpTimestampGenerator for Timestamp {
fn init(&mut self) {
// ...
}
fn timestamp_sec(&self) -> u64 {
0u64
}
fn timestamp_subsec_micros(&self) -> u32 {
0u32
}
}
impl Default for Timestamp {
fn default() -> Self {
Self {}
}
}
fn main() {
let socket =
UdpSocket::bind("0.0.0.0:0").expect("Unable to crate UDP socket");
let context = NtpContext::new(Timestamp::default());
let server_addr: SocketAddr = "time.google.com:123"
.to_socket_addrs()
.expect("Unable to resolve host")
.next()
.unwrap();
match executor
.block_on(async { get_time(server_addr, &socket, context).await })
{
Ok(response_result) => {
println!("Response processed: {response_result:?}")
}
Err(err) => eprintln!("Error: {err:?}"),
}
}For more complex example with a custom timestamp generator and UDP socket implementation, see
examples/smoltcp-request.
For usage SNTP-client in an asynchronous environment, see examples/tokio
Modules§
- net
- Network types used by the
sntpccrate
Structs§
- NtpContext
- SNTP client context that contains of objects that may be required for client’s operation
- NtpResult
- SNTP request result representation
- Send
Request Result - Preserve SNTP request sending operation result required during receiving and processing state
- StdTimestamp
Gen - Standard library timestamp generator wrapper type
that relies on
std::timeto provide timestamps during SNTP client operations
Enums§
- Error
- The error type for SNTP client Errors originate on network layer or during processing response from a NTP server
Traits§
- NtpTimestamp
Generator - A trait encapsulating timestamp generator’s operations
- NtpUdp
Socket - A trait encapsulating UDP socket interface required for SNTP client operations
Functions§
- fraction_
to_ microseconds - Convert second fraction value to microseconds value
- fraction_
to_ milliseconds - Convert second fraction value to milliseconds value
- fraction_
to_ nanoseconds - Convert second fraction value to nanoseconds value
- fraction_
to_ picoseconds - Convert second fraction value to picoseconds value
- get_
time - Retrieves the current time from an NTP server.
- sntp_
process_ response - Processes the response from an NTP server.
- sntp_
send_ request - Sends an SNTP request to an NTP server.
Type Aliases§
- Result
- SNTP library result type