Skip to content

Commit 8391b17

Browse files
committed
More responsive packet polling loop
- Don't use delay to wait for a packet; instead use a tight loop and yield() - Mark the millis' at the start and end of the loop; use that to calculate the relative update time - Reject packets of the incorrect size
1 parent 479f290 commit 8391b17

File tree

1 file changed

+23
-7
lines changed

1 file changed

+23
-7
lines changed

NTPClient.cpp

+23-7
Original file line numberDiff line numberDiff line change
@@ -93,16 +93,32 @@ bool NTPClient::forceUpdate() {
9393
this->sendNTPPacket();
9494
this->_packetSent = true;
9595

96-
// Wait till data is there or timeout...
97-
byte timeout = 0;
96+
// Wait 500ms till data is there or timeout...
97+
unsigned long ts_start = millis();
98+
unsigned long ts_end = ts_start;
9899
int cb = 0;
99-
do {
100-
if (timeout++ > 100) return false; // timeout after 1000 ms
101-
delay ( 10 );
100+
while ((ts_end - ts_start) < 500) {
102101
cb = this->_udp->parsePacket();
103-
} while (cb == 0);
102+
if (cb != 0)
103+
break;
104+
yield();
105+
ts_end = millis();
106+
}
107+
108+
if (cb <= 0) // no data, error or timed out
109+
return false;
110+
111+
if (cb != NTP_PACKET_SIZE) {
112+
// unexpected packet size
113+
this->_udp->flush();
114+
return false;
115+
}
104116

105-
this->_lastUpdate = millis() - (5 * timeout); // Account for delay in reading the time
117+
// Use half the time taken to get the update;; if we assume
118+
// symmetric latency, it would be roughly correct.
119+
// Ideally we'd do the proper two-NTP query thing and
120+
// subtract the rx/tx times to work this out really correctly.
121+
this->_lastUpdate = ts_start + ((ts_end - ts_start) / 2);
106122

107123
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
108124

0 commit comments

Comments
 (0)