Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Close UDP socket after communicating with NTPServer #6

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions src/EasyNTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -46,17 +46,22 @@ unsigned long EasyNTPClient::getServerTime () {
const long ntpFirstFourBytes = 0xEC0600E3; // NTP request header

// Fail if WiFiUdp.begin() could not init a socket
if (! udpInited)
return 0;
if (! udpInited) {
this->mUdp->stop();
return 0;
}

// Clear received data from possible stray received packets
this->mUdp->flush();

// Send an NTP request
if (! (this->mUdp->beginPacket(this->mServerPool, 123) // 123 is the NTP port
&& this->mUdp->write((byte *)&ntpFirstFourBytes, 48) == 48
&& this->mUdp->endPacket()))
return 0; // sending request failed
&& this->mUdp->endPacket())) {
this->mUdp->stop();
return 0; // sending request failed
}


// Wait for response; check every pollIntv ms up to maxPoll times
const int pollIntv = 150; // poll every this many ms
Expand All @@ -67,8 +72,10 @@ unsigned long EasyNTPClient::getServerTime () {
break;
delay(pollIntv);
}
if (pktLen != 48)
return 0; // no correct packet received
if (pktLen != 48) {
this->mUdp->stop();
return 0; // no correct packet received
}

// Read and discard the first useless bytes
// Set useless to 32 for speed; set to 40 for accuracy.
Expand All @@ -91,6 +98,7 @@ unsigned long EasyNTPClient::getServerTime () {

// Discard the rest of the packet
this->mUdp->flush();
this->mUdp->stop();

return time + this->mOffset - 2208988800ul; // convert NTP time to Unix time
}
Expand Down