Crate sntpc

Source
Expand description

Rust SNTP client

§Overview

This crate provides a method for sending requests to NTP servers and process responses, extracting received timestamp. Supported SNTP protocol versions:

§Usage

Put this in your Cargo.toml:

[dependencies]
sntpc = "0.5"

§Features

sntpc supports several features:

  • std: includes functionality that depends on the standard library
  • sync: enables synchronous interface
  • utils: includes functionality that mostly OS specific and allows system time sync
  • log: enables library debug output during execution
  • defmt: enables library debug output using defmt
  • std-socket: add NtpUdpSocket trait implementation for std::net::UdpSocket
  • embassy-socket: add NtpUdpSocket trait implementation for embassy_net::udp::UdpSocket
  • tokio-socket: add NtpUdpSocket trait implementation for tokio::net::UdpSocket

Warning: log and defmt are mutually exclusive features. If for some reason both are enabled defmt is considered to have 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 how the library can be used:

  • under environments where a networking stuff is hidden in system/RTOS kernel, get_time can be used since it encapsulates network I/O
  • under environments where TCP/IP stack requires to call some helper functions like poll, wait, etc. and/or there are no options to perform I/O operations within a single call, sntp_send_request and sntp_process_response can 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:

  • NtpUdpSocket trait should be implemented for UdpSocket-like objects for the library to be able to send and receive data from NTP servers
  • NtpTimestampGenerator trait 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 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 sntpc crate

Structs§

NtpContext
SNTP client context that contains of objects that may be required for client’s operation
NtpResult
SNTP request result representation
SendRequestResult
Preserve SNTP request sending operation result required during receiving and processing state
StdTimestampGen
Standard library timestamp generator wrapper type that relies on std::time to 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§

NtpTimestampGenerator
A trait encapsulating timestamp generator’s operations
NtpUdpSocket
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