Skip to content

Commit 5a93a54

Browse files
committed
Add more error checking.
1 parent 78d4237 commit 5a93a54

File tree

2 files changed

+17
-8
lines changed

2 files changed

+17
-8
lines changed

NTPClient.cpp

+16-7
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,8 @@ bool NTPClient::forceUpdate() {
9090
while(this->_udp->parsePacket() != 0)
9191
this->_udp->flush();
9292

93-
this->sendNTPPacket();
93+
if (!this->sendNTPPacket())
94+
return false;
9495

9596
// Wait till data is there or timeout...
9697
byte timeout = 0;
@@ -104,7 +105,8 @@ bool NTPClient::forceUpdate() {
104105

105106
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
106107

107-
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
108+
if (this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE) != NTP_PACKET_SIZE)
109+
return false;
108110

109111
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
110112
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
@@ -181,7 +183,7 @@ void NTPClient::setPoolServerName(const char* poolServerName) {
181183
this->_poolServerName = poolServerName;
182184
}
183185

184-
void NTPClient::sendNTPPacket() {
186+
bool NTPClient::sendNTPPacket() {
185187
// set all bytes in the buffer to 0
186188
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
187189
// Initialize values needed to form NTP request
@@ -197,13 +199,20 @@ void NTPClient::sendNTPPacket() {
197199

198200
// all NTP fields have been given values, now
199201
// you can send a packet requesting a timestamp:
202+
203+
bool success = false;
200204
if (this->_poolServerName) {
201-
this->_udp->beginPacket(this->_poolServerName, 123);
205+
success = this->_udp->beginPacket(this->_poolServerName, 123);
202206
} else {
203-
this->_udp->beginPacket(this->_poolServerIP, 123);
207+
success = this->_udp->beginPacket(this->_poolServerIP, 123);
204208
}
205-
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
206-
this->_udp->endPacket();
209+
210+
if (success)
211+
if (this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE) == NTP_PACKET_SIZE)
212+
if (this->_udp->endPacket())
213+
return true;
214+
215+
return false;
207216
}
208217

209218
void NTPClient::setRandomPort(unsigned int minValue, unsigned int maxValue) {

NTPClient.h

+1-1
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ class NTPClient {
2525

2626
byte _packetBuffer[NTP_PACKET_SIZE];
2727

28-
void sendNTPPacket();
28+
bool sendNTPPacket();
2929

3030
public:
3131
NTPClient(UDP& udp);

0 commit comments

Comments
 (0)