Skip to content

Commit 5ba93ed

Browse files
authored
Merge pull request #45
Clean up
2 parents 1f0de17 + 4de151c commit 5ba93ed

File tree

10 files changed

+106
-107
lines changed

10 files changed

+106
-107
lines changed

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ fn main() {
5656
.set_read_timeout(Some(Duration::from_secs(2)))
5757
.expect("Unable to set UDP socket read timeout");
5858

59-
for addr in POOL_NTP_ADDR.to_socket_addrs().filter(SocketAddr::is_ipv4).unwrap() {
59+
for addr in POOL_NTP_ADDR.to_socket_addrs().unwrap() {
6060
let ntp_context = NtpContext::new(StdTimestampGen::default());
6161
let result = get_time(addr, &socket, ntp_context);
6262

examples/simple-request/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ edition = "2021"
55
publish = false
66

77
[features]
8-
log = ["dep:simple_logger", "dep:log"]
8+
log = ["dep:simple_logger", "dep:log", "sntpc/log"]
99

1010
[dependencies]
1111
sntpc = { path = "../../sntpc", features = ["sync"] }

examples/smoltcp-request/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ edition = "2021"
55
publish = false
66

77
[features]
8-
log = ["dep:simple_logger", "dep:log"]
8+
log = ["dep:simple_logger", "dep:log", "sntpc/log"]
99

1010
[dependencies]
1111
sntpc = { path = "../../sntpc", features = ["sync"] }

examples/timesync/Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ edition = "2021"
55
publish = false
66

77
[features]
8-
log = ["dep:simple_logger", "dep:log"]
8+
log = ["dep:simple_logger", "dep:log", "sntpc/log"]
99

1010
[dependencies]
1111
sntpc = { path = "../../sntpc", default-features = false, features = ["utils", "sync"] }

sntpc/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ miniloop = { version = "~0.3", optional = true }
3737
embassy-net = { version = "0.5.0", features = ["udp", "proto-ipv4", "proto-ipv6", "medium-ip"], optional = true }
3838
tokio = { version = "1", features = ["net"], optional = true }
3939
defmt = { version = "0.3", optional = true }
40+
cfg-if = "~1"
4041

4142
[dev-dependencies]
4243
miniloop = "~0.3"

sntpc/src/lib.rs

+12-80
Original file line numberDiff line numberDiff line change
@@ -151,13 +151,14 @@
151151
#[cfg(feature = "utils")]
152152
pub mod utils;
153153

154+
mod log;
154155
mod socket;
155156
mod types;
156157

157158
pub use crate::types::*;
158159

159160
#[cfg(any(feature = "log", feature = "defmt"))]
160-
use core::str;
161+
use crate::log::debug;
161162

162163
/// Network types used by the `sntpc` crate
163164
pub mod net {
@@ -167,10 +168,7 @@ pub mod net {
167168
pub use std::net::UdpSocket;
168169
}
169170

170-
#[cfg(feature = "defmt")]
171-
use defmt::debug;
172-
#[cfg(all(feature = "log", not(feature = "defmt")))]
173-
use log::debug;
171+
use cfg_if::cfg_if;
174172

175173
/// Retrieves the current time from an NTP server.
176174
///
@@ -605,19 +603,15 @@ where
605603
/// Synchronous interface for the SNTP client
606604
#[cfg(feature = "sync")]
607605
pub mod sync {
606+
#[cfg(any(feature = "log", feature = "defmt"))]
607+
use crate::log::debug;
608608
use crate::net;
609609
use crate::types::{
610610
NtpContext, NtpResult, NtpTimestampGenerator, NtpUdpSocket, Result,
611611
SendRequestResult,
612612
};
613613

614614
use miniloop::executor::Executor;
615-
616-
#[cfg(feature = "defmt")]
617-
use defmt::debug;
618-
#[cfg(all(feature = "log", not(feature = "defmt")))]
619-
use log::debug;
620-
621615
/// Send request to a NTP server with the given address and process the response in a single call
622616
///
623617
/// May be useful under an environment with `std` networking implementation, where all
@@ -814,7 +808,6 @@ pub mod sync {
814808
/// // you would want to fix destination address, since string hostname may resolve to
815809
/// // different IP addresses
816810
/// let addr = "time.google.com:123".to_socket_addrs().unwrap().filter(SocketAddr::is_ipv4).next().unwrap();
817-
///
818811
/// let send_request_result = sntpc::sync::sntp_send_request(addr, &socket, context).unwrap();
819812
/// let result = sntpc::sync::sntp_process_response(addr, &socket, context, send_request_result);
820813
///
@@ -858,8 +851,13 @@ fn process_response(
858851
let mut packet = NtpPacket::from(resp);
859852

860853
convert_from_network(&mut packet);
861-
#[cfg(any(feature = "log", feature = "defmt"))]
862-
debug_ntp_packet(&packet, recv_timestamp);
854+
855+
cfg_if!(
856+
if #[cfg(any(feature = "log", feature = "defmt"))] {
857+
let debug_packet = DebugNtpPacket::new(&packet, recv_timestamp);
858+
debug!("{:#?}", debug_packet);
859+
}
860+
);
863861

864862
if send_req_result.originate_timestamp != packet.origin_timestamp {
865863
return Err(Error::IncorrectOriginTimestamp);
@@ -994,72 +992,6 @@ fn offset_calculate(t1: u64, t2: u64, t3: u64, t4: u64, units: Units) -> i64 {
994992
}
995993
}
996994

997-
#[cfg(feature = "defmt")]
998-
fn debug_ntp_packet(packet: &NtpPacket, recv_timestamp: u64) {
999-
let mode = shifter(packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
1000-
let version = shifter(packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
1001-
let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);
1002-
1003-
debug!("NTP Packet:");
1004-
debug!("Mode: {}", mode);
1005-
debug!("Version: {}", version);
1006-
debug!("Leap: {}", li);
1007-
debug!("Stratum: {}", packet.stratum);
1008-
debug!("Poll: {}", packet.poll);
1009-
debug!("Precision: {}", packet.precision);
1010-
debug!("Root delay: {}", packet.root_delay);
1011-
debug!("Root dispersion: {}", packet.root_dispersion);
1012-
debug!(
1013-
"Reference ID: {}",
1014-
str::from_utf8(&packet.ref_id.to_be_bytes()).unwrap_or("")
1015-
);
1016-
debug!("Origin timestamp (client): {}", packet.origin_timestamp);
1017-
debug!("Receive timestamp (server): {}", packet.recv_timestamp);
1018-
debug!("Transmit timestamp (server): {}", packet.tx_timestamp);
1019-
debug!("Receive timestamp (client): {}", recv_timestamp);
1020-
debug!("Reference timestamp (server): {}", packet.ref_timestamp);
1021-
}
1022-
1023-
#[cfg(all(feature = "log", not(feature = "defmt")))]
1024-
fn debug_ntp_packet(packet: &NtpPacket, recv_timestamp: u64) {
1025-
let mode = shifter(packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
1026-
let version = shifter(packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
1027-
let li = shifter(packet.li_vn_mode, LI_MASK, LI_SHIFT);
1028-
let delimiter_gen = || unsafe { str::from_utf8_unchecked(&[b'='; 64]) };
1029-
1030-
debug!("{}", delimiter_gen());
1031-
debug!("| Mode:\t\t{}", mode);
1032-
debug!("| Version:\t{}", version);
1033-
debug!("| Leap:\t\t{}", li);
1034-
debug!("| Stratum:\t{}", packet.stratum);
1035-
debug!("| Poll:\t\t{}", packet.poll);
1036-
debug!("| Precision:\t\t{}", packet.precision);
1037-
debug!("| Root delay:\t\t{}", packet.root_delay);
1038-
debug!("| Root dispersion:\t{}", packet.root_dispersion);
1039-
debug!(
1040-
"| Reference ID:\t\t{}",
1041-
str::from_utf8(&packet.ref_id.to_be_bytes()).unwrap_or("")
1042-
);
1043-
debug!(
1044-
"| Origin timestamp (client):\t{:>16}",
1045-
packet.origin_timestamp
1046-
);
1047-
debug!(
1048-
"| Receive timestamp (server):\t{:>16}",
1049-
packet.recv_timestamp
1050-
);
1051-
debug!(
1052-
"| Transmit timestamp (server):\t{:>16}",
1053-
packet.tx_timestamp
1054-
);
1055-
debug!("| Receive timestamp (client):\t{:>16}", recv_timestamp);
1056-
debug!(
1057-
"| Reference timestamp (server):\t{:>16}",
1058-
packet.ref_timestamp
1059-
);
1060-
debug!("{}", delimiter_gen());
1061-
}
1062-
1063995
fn get_ntp_timestamp<T: NtpTimestampGenerator>(timestamp_gen: &T) -> u64 {
1064996
((timestamp_gen.timestamp_sec()
1065997
+ (u64::from(NtpPacket::NTP_TIMESTAMP_DELTA)))

sntpc/src/log.rs

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
#![allow(unused_imports)]
2+
use cfg_if::cfg_if;
3+
4+
cfg_if! {
5+
if #[cfg(feature = "defmt")] {
6+
pub(crate) use defmt::{debug, error};
7+
} else if #[cfg(feature = "log")] {
8+
pub(crate) use log::{debug, error};
9+
}
10+
}

sntpc/src/socket/embassy.rs

+2-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
1+
#[cfg(any(feature = "log", feature = "defmt"))]
2+
use crate::log::error;
13
use crate::{net::SocketAddr, Error, NtpUdpSocket, Result};
24
use embassy_net::{udp::UdpSocket, IpAddress, IpEndpoint};
35

46
use core::net::IpAddr;
57

6-
#[cfg(feature = "defmt")]
7-
use defmt::error;
8-
#[cfg(all(feature = "log", not(feature = "defmt")))]
9-
use log::error;
10-
118
impl NtpUdpSocket for UdpSocket<'_> {
129
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> Result<usize> {
1310
// Currently smoltcp still has its own address enum

sntpc/src/types.rs

+74-13
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,14 @@
1+
use crate::get_ntp_timestamp;
2+
#[cfg(any(feature = "log", feature = "defmt"))]
3+
use crate::log::debug;
4+
use crate::net::SocketAddr;
5+
6+
use cfg_if::cfg_if;
7+
18
use core::fmt::Formatter;
29
use core::fmt::{Debug, Display};
3-
use core::mem;
4-
510
use core::future::Future;
6-
#[cfg(feature = "defmt")]
7-
use defmt::debug;
8-
#[cfg(all(feature = "log", not(feature = "defmt")))]
9-
use log::debug;
10-
11-
use crate::get_ntp_timestamp;
12-
use crate::net::SocketAddr;
11+
use core::mem;
1312

1413
/// SNTP mode value bit mask
1514
pub(crate) const MODE_MASK: u8 = 0b0000_0111;
@@ -39,7 +38,6 @@ pub(crate) const SECONDS_FRAC_MASK: u64 = 0xffff_ffff;
3938
/// SNTP library result type
4039
pub type Result<T> = core::result::Result<T, Error>;
4140

42-
#[derive(Debug)]
4341
pub(crate) struct NtpPacket {
4442
pub(crate) li_vn_mode: u8,
4543
pub(crate) stratum: u8,
@@ -54,6 +52,68 @@ pub(crate) struct NtpPacket {
5452
pub(crate) tx_timestamp: u64,
5553
}
5654

55+
cfg_if! {
56+
if #[cfg(any(feature = "log", feature = "defmt"))] {
57+
use crate::shifter;
58+
59+
use core::str;
60+
61+
pub(crate) struct DebugNtpPacket<'a> {
62+
packet: &'a NtpPacket,
63+
client_recv_timestamp: u64,
64+
}
65+
66+
impl<'a> DebugNtpPacket<'a> {
67+
pub(crate) fn new(
68+
packet: &'a NtpPacket,
69+
client_recv_timestamp: u64,
70+
) -> Self {
71+
Self {
72+
packet,
73+
client_recv_timestamp,
74+
}
75+
}
76+
}
77+
78+
impl Debug for DebugNtpPacket<'_> {
79+
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
80+
let mode = shifter(self.packet.li_vn_mode, MODE_MASK, MODE_SHIFT);
81+
let version =
82+
shifter(self.packet.li_vn_mode, VERSION_MASK, VERSION_SHIFT);
83+
let li = shifter(self.packet.li_vn_mode, LI_MASK, LI_SHIFT);
84+
let id_slice = &self.packet.ref_id.to_be_bytes();
85+
let reference_id = str::from_utf8(id_slice).unwrap_or("");
86+
87+
f.debug_struct("NtpPacket")
88+
.field("mode", &mode)
89+
.field("version", &version)
90+
.field("leap", &li)
91+
.field("stratum", &self.packet.stratum)
92+
.field("poll", &self.packet.poll)
93+
.field("precision", &self.packet.precision)
94+
.field("root delay", &self.packet.root_delay)
95+
.field("root dispersion", &self.packet.root_dispersion)
96+
.field("reference ID", &reference_id)
97+
.field(
98+
"origin timestamp (client)",
99+
&self.packet.origin_timestamp,
100+
)
101+
.field(
102+
"receive timestamp (server)",
103+
&self.packet.recv_timestamp,
104+
)
105+
.field(
106+
"transmit timestamp (server)",
107+
&self.packet.tx_timestamp,
108+
)
109+
.field("receive timestamp (client)", &self.client_recv_timestamp)
110+
.field("reference timestamp (server)", &self.packet.ref_timestamp)
111+
.finish()
112+
}
113+
}
114+
}
115+
}
116+
57117
#[derive(Debug, Copy, Clone)]
58118
pub(crate) struct NtpTimestamp {
59119
pub(crate) seconds: i64,
@@ -214,12 +274,12 @@ impl NtpPacket {
214274
const SNTP_CLIENT_MODE: u8 = 3;
215275
const SNTP_VERSION: u8 = 4 << 3;
216276

217-
pub fn new<T: NtpTimestampGenerator>(mut timestamp_gen: T) -> NtpPacket {
277+
pub fn new<T: NtpTimestampGenerator>(mut timestamp_gen: T) -> Self {
218278
timestamp_gen.init();
219279
let tx_timestamp = get_ntp_timestamp(&timestamp_gen);
220280

221281
#[cfg(any(feature = "log", feature = "defmt"))]
222-
debug!("NtpPacket::new({})", tx_timestamp);
282+
debug!("NtpPacket::new(tx_timestamp: {})", tx_timestamp);
223283

224284
NtpPacket {
225285
li_vn_mode: NtpPacket::SNTP_CLIENT_MODE | NtpPacket::SNTP_VERSION,
@@ -408,6 +468,7 @@ impl From<RawNtpPacket> for NtpPacket {
408468
// temp_buf.copy_from_slice(x);
409469
// temp_buf
410470
// }
471+
// see: https://github.com/vpetrigo/sntpc/issues/34
411472
let to_array_u32 = |x: &[u8]| {
412473
let mut temp_buf = [0u8; mem::size_of::<u32>()];
413474
temp_buf.copy_from_slice(x);
@@ -440,7 +501,7 @@ impl From<RawNtpPacket> for NtpPacket {
440501
impl From<&NtpPacket> for RawNtpPacket {
441502
#[allow(clippy::cast_sign_loss)]
442503
fn from(val: &NtpPacket) -> Self {
443-
let mut tmp_buf = [0u8; mem::size_of::<NtpPacket>()];
504+
let mut tmp_buf = [0u8; size_of::<NtpPacket>()];
444505

445506
tmp_buf[0] = val.li_vn_mode;
446507
tmp_buf[1] = val.stratum;

sntpc/src/utils.rs

+3-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
11
//! Helper utils to synchronize time of a system
22
//!
33
//! Currently, Unix and Windows based systems are supported
4-
#[cfg(feature = "log")]
4+
#[cfg(any(feature = "log", feature = "defmt"))]
5+
use crate::log::debug;
6+
#[cfg(any(feature = "log", feature = "defmt"))]
57
use chrono::Timelike;
68
use chrono::{Local, TimeZone, Utc};
7-
#[cfg(feature = "defmt")]
8-
use defmt::debug;
9-
#[cfg(all(feature = "log", not(feature = "defmt")))]
10-
use log::debug;
119

1210
#[cfg(unix)]
1311
use unix::sync_time;

0 commit comments

Comments
 (0)