-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathntp.cpp
More file actions
215 lines (175 loc) · 4.16 KB
/
ntp.cpp
File metadata and controls
215 lines (175 loc) · 4.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
#include "ntp.h"
NTP::NTP(UDP &sock)
: _sock(sock),
_address("pool.ntp.org")
{
}
NTP::NTP(UDP &sock, const char *address)
: _sock(sock),
_address(address ? address : "pool.ntp.org")
{
}
void NTP::begin(uint16_t port)
{
_sock.begin(port);
}
void NTP::end()
{
_sock.stop();
}
void NTP::setServer(const char *address)
{
if (address && address[0] != '\0')
{
_address = address;
}
}
void NTP::setTimeOffset(int32_t timeOffsetSeconds)
{
_timeOffset = timeOffsetSeconds;
}
bool NTP::isValid() const
{
return _valid;
}
uint32_t NTP::_nowUtc() const
{
if (!_valid)
{
return 0;
}
// handle millis() rollover by unsigned arithmetic
uint32_t nowMs = millis();
uint32_t elapsed = (nowMs - _lastSyncMillis) / 1000;
return _timestamp + elapsed;
}
uint32_t NTP::getTimestamp() const
{
return _nowUtc(); // pure UTC
}
uint32_t NTP::getEpochTime() const
{
if (!_valid)
{
return 0;
}
uint32_t utc = _nowUtc();
int32_t local = (int32_t)utc + _timeOffset;
if (local < 0)
{
// Before 1970; clamp to 0 to avoid underflow on cast
return 0;
}
return (uint32_t)local;
}
bool NTP::update(uint16_t timeoutMs)
{
// Clear any pending packets from previous tries
while (_sock.parsePacket() > 0)
{
_sock.flush();
}
uint8_t *b = _buffer;
memset(b, 0, NTP_PACKET_SIZE);
// NTP header:
// LI (2 bits) = 0 (no warning)
// VN (3 bits) = 4 (version 4)
// Mode (3 bits) = 3 (client)
b[0] = 0b00100011; // 0x23
b[1] = 0; // Stratum (unspecified)
b[2] = 6; // Polling interval (not critical for simple client)
b[3] = 0xEC; // Peer clock precision (example value)
// "1N14" magic reference ID
b[12] = 0x31;
b[13] = 0x4E;
b[14] = 0x31;
b[15] = 0x34;
// Send request to NTP server (port 123)
if (!_sock.beginPacket(_address, 123))
{
return false;
}
_sock.write(b, NTP_PACKET_SIZE);
_sock.endPacket();
// Wait for response with proper timeout
uint32_t start = millis();
int packetSize = 0;
do
{
delay(10);
packetSize = _sock.parsePacket();
if ((millis() - start) >= timeoutMs)
{
return false; // timeout
}
} while (packetSize == 0);
// Basic sanity check: full NTP packet
if (packetSize < NTP_PACKET_SIZE)
{
_sock.flush();
return false;
}
_sock.read(_buffer, NTP_PACKET_SIZE);
const uint8_t *r = _buffer;
// Validate response mode and version
const uint8_t li = (r[0] >> 6) & 0x03;
const uint8_t vn = (r[0] >> 3) & 0x07;
const uint8_t mode = r[0] & 0x07;
// mode should be 4 (server) or 5 (broadcast); vn >= 3 typical
if (mode != 4 && mode != 5)
{
return false;
}
if (vn < 3 || li == 3)
{
// Unsynchronized server or very old version
return false;
}
// Bytes 40..43: Transmit Timestamp (high 32 bits: seconds since 1900-01-01)
uint32_t ntpSeconds =
((uint32_t)r[40] << 24) |
((uint32_t)r[41] << 16) |
((uint32_t)r[42] << 8) |
((uint32_t)r[43]);
if (ntpSeconds < NTP_TIMESTAMP_DIFFERENCE)
{
// Should never happen for real NTP servers; sanity check
return false;
}
_timestamp = ntpSeconds - NTP_TIMESTAMP_DIFFERENCE; // UTC seconds since 1970-01-01
_lastSyncMillis = millis();
_valid = true;
return true;
}
ntp_datetime_t NTP::getDateTime() const
{
ntp_datetime_t r = {0, 0, 0, 0, 0, 0};
if (!_valid)
{
return r;
}
uint32_t s = getEpochTime(); // local time (with offset)
if (s == 0)
{
return r;
}
// Day/date calculation:
// Based on Howard Hinnant's "civil_from_days" algorithm
uint32_t z = s / 86400 + 719468; // days since 0000-03-01
uint32_t era = z / 146097;
uint32_t doe = z - era * 146097; // [0, 146096]
uint32_t yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
uint32_t y = yoe + era * 400;
uint32_t doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
uint32_t mp = (5 * doy + 2) / 153;
uint32_t d = doy - (153 * mp + 2) / 5 + 1;
uint32_t m = mp + (mp < 10 ? 3 : -9);
y += (m <= 2);
r.year = (uint16_t)y;
r.month = (uint8_t)m;
r.day = (uint8_t)d;
r.hour = (uint8_t)((s % 86400) / 3600);
r.minute = (uint8_t)((s % 3600) / 60);
r.second = (uint8_t)(s % 60);
return r;
}