NTPClient now does updates asynchronously. Thanks to https://github.com/arduino-libraries/NTPClient/pull/22

This commit is contained in:
Fabian Schlenz 2019-05-31 23:58:34 +02:00
parent f9fba8a8f9
commit 29e136b8db
2 changed files with 151 additions and 69 deletions

View File

@ -5,48 +5,53 @@
#include <Udp.h> #include <Udp.h>
#define SEVENZYYEARS 2208988800UL #define SEVENZYYEARS 2208988800UL
#define FRACTIONSPERMILLI (4294967UL)
#define NTP_PACKET_SIZE 48 #define NTP_PACKET_SIZE 48
#define NTP_DEFAULT_LOCAL_PORT 1337 #define NTP_DEFAULT_LOCAL_PORT 1337
class NTPClient;
typedef void (*NTPUpdateCallbackFunction)(NTPClient* c);
class NTPClient { class NTPClient {
private: private:
UDP* _udp; UDP* _udp;
bool _udpSetup = false; bool _udpSetup = false;
const char* _poolServerName = "pool.ntp.org"; // Default time server const char* _poolServerName = "time.nist.gov"; // Default time server
int _port = NTP_DEFAULT_LOCAL_PORT; int _port = NTP_DEFAULT_LOCAL_PORT;
long _timeOffset = 0; int _timeOffset = 0;
bool _timeValid = false;
unsigned long _updateInterval = 60000; // In ms unsigned int _updateInterval = 60000; // In ms
unsigned int _retryInterval = 1000; // In ms
unsigned long _currentEpoc = 0; // In s unsigned long _currentEpoc = 0; // In s
unsigned long _currentFraction = 0; // In 1/(2^32) s
unsigned long _lastUpdate = 0; // In ms unsigned long _lastUpdate = 0; // In ms
unsigned long _lastRequest = 0; // IN ms
byte _packetBuffer[NTP_PACKET_SIZE]; byte _packetBuffer[NTP_PACKET_SIZE];
void sendNTPPacket(); NTPUpdateCallbackFunction _updateCallback = NULL;
boolean _timeValid = false; void sendNTPPacket();
bool checkResponse();
public: public:
NTPClient(UDP& udp); NTPClient(UDP& udp);
NTPClient(UDP& udp, long timeOffset); NTPClient(UDP& udp, int timeOffset);
NTPClient(UDP& udp, const char* poolServerName); NTPClient(UDP& udp, const char* poolServerName);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset); NTPClient(UDP& udp, const char* poolServerName, int timeOffset);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval); NTPClient(UDP& udp, const char* poolServerName, int timeOffset, int updateInterval);
/**
* Set time server name
*
* @param poolServerName
*/
void setPoolServerName(const char* poolServerName);
/** /**
* Starts the underlying UDP client with the default local port * Starts the underlying UDP client with the default local port
*/ */
void begin(); void begin();
bool getTimeValid();
/** /**
* Starts the underlying UDP client with the specified local port * Starts the underlying UDP client with the specified local port
*/ */
@ -61,17 +66,28 @@ class NTPClient {
bool update(); bool update();
/** /**
* This will force the update from the NTP Server. * Has the time ever been sucessfully updated
* *
*/
bool updated();
/**
* Register a callback function for when the time gets updated
*
*/
void setUpdateCallback(NTPUpdateCallbackFunction f);
/**
* This will force the update from the NTP Server.
* This can block for a full second
* @return true on success, false on failure * @return true on success, false on failure
*/ */
bool forceUpdate(); bool forceUpdate();
int getDay() const; int getDay();
int getHours() const; int getHours();
int getMinutes() const; int getMinutes();
int getSeconds() const; int getSeconds();
boolean getTimeValid() const;
/** /**
* Changes the time offset. Useful for changing timezones dynamically * Changes the time offset. Useful for changing timezones dynamically
@ -82,17 +98,27 @@ class NTPClient {
* Set the update interval to another frequency. E.g. useful when the * Set the update interval to another frequency. E.g. useful when the
* timeOffset should not be set in the constructor * timeOffset should not be set in the constructor
*/ */
void setUpdateInterval(unsigned long updateInterval); void setUpdateInterval(int updateInterval);
/**
* Set the retry interval to another frequency in ms
*/
void setRetryInterval(int retryInterval);
/** /**
* @return time formatted like `hh:mm:ss` * @return time formatted like `hh:mm:ss`
*/ */
String getFormattedTime() const; String getFormattedTime();
/** /**
* @return time in seconds since Jan. 1, 1970 * @return time in seconds since Jan. 1, 1970
*/ */
unsigned long getEpochTime() const; unsigned long getEpochTime();
/**
* @return time in milliseconds since Jan. 1, 1970
*/
unsigned long long getEpochMillis();
/** /**
* Stops the underlying UDP client * Stops the underlying UDP client

View File

@ -26,7 +26,7 @@ NTPClient::NTPClient(UDP& udp) {
this->_udp = &udp; this->_udp = &udp;
} }
NTPClient::NTPClient(UDP& udp, long timeOffset) { NTPClient::NTPClient(UDP& udp, int timeOffset) {
this->_udp = &udp; this->_udp = &udp;
this->_timeOffset = timeOffset; this->_timeOffset = timeOffset;
} }
@ -36,13 +36,13 @@ NTPClient::NTPClient(UDP& udp, const char* poolServerName) {
this->_poolServerName = poolServerName; this->_poolServerName = poolServerName;
} }
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset) { NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset) {
this->_udp = &udp; this->_udp = &udp;
this->_timeOffset = timeOffset; this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName; this->_poolServerName = poolServerName;
} }
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval) { NTPClient::NTPClient(UDP& udp, const char* poolServerName, int timeOffset, int updateInterval) {
this->_udp = &udp; this->_udp = &udp;
this->_timeOffset = timeOffset; this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName; this->_poolServerName = poolServerName;
@ -61,79 +61,128 @@ void NTPClient::begin(int port) {
this->_udpSetup = true; this->_udpSetup = true;
} }
bool NTPClient::checkResponse() {
if (this->_udp->parsePacket()) {
this->_lastUpdate = millis();
this->_lastRequest = 0; // no outstanding request
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
highWord = word(this->_packetBuffer[44], this->_packetBuffer[45]);
lowWord = word(this->_packetBuffer[46], this->_packetBuffer[47]);
this->_currentFraction = highWord << 16 | lowWord;
random16_add_entropy(this->_packetBuffer[44]<<8 | this->_packetBuffer[45]);
random16_add_entropy(this->_packetBuffer[46]<<8 | this->_packetBuffer[47]);
// if the user has set a callback function for when the time is updated, call it
if (_updateCallback) { _updateCallback(this); }
this->_timeValid = true;
return true;
} else {
return false;
}
}
bool NTPClient::forceUpdate() { bool NTPClient::forceUpdate() {
#ifdef DEBUG_NTPClient #ifdef DEBUG_NTPClient
Serial.println("Update from NTP Server"); Serial.println("Update from NTP Server");
#endif #endif
while(this->_udp->parsePacket() != 0) this->_timeValid = false;
this->_udp->flush();
while(this->_udp->parsePacket() != 0) this->_udp->flush();
this->sendNTPPacket(); this->sendNTPPacket();
// Wait till data is there or timeout... // Wait till data is there or timeout...
byte timeout = 0; byte timeout = 0;
int cb = 0; bool cb = 0;
do { do {
delay ( 10 ); delay ( 10 );
cb = this->_udp->parsePacket(); cb = this->checkResponse();
if (timeout > 100) { if (timeout > 100) return false; // timeout after 1000 ms
this->_timeValid = false;
return false; // timeout after 1000 ms
}
timeout++; timeout++;
} while (cb == 0); } while (cb == false);
this->_timeValid = true;
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
random16_add_entropy(this->_packetBuffer[44]<<8 | this->_packetBuffer[45]);
random16_add_entropy(this->_packetBuffer[46]<<8 | this->_packetBuffer[47]);
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
return true; return true;
} }
bool NTPClient::update() { bool NTPClient::update() {
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval bool updated = false;
|| this->_lastUpdate == 0) { // Update if there was no update yet. unsigned long now = millis();
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
return this->forceUpdate(); if ( ((_lastRequest == 0) && (_lastUpdate == 0)) // Never requested or updated
|| ((_lastRequest == 0) && ((now - _lastUpdate) >= _updateInterval)) // Update after _updateInterval
|| ((_lastRequest != 0) && ((now - _lastRequest) > _retryInterval)) ) { // Update if there was no response to the request
this->_timeValid = false;
// setup the UDP client if needed
if (!this->_udpSetup) {
this->begin();
}
this->sendNTPPacket();
} }
return true;
if (_lastRequest) {
updated = checkResponse();
}
return updated;
} }
unsigned long NTPClient::getEpochTime() const { bool NTPClient::updated() {
return (_currentEpoc != 0);
}
bool NTPClient::getTimeValid() {
return this->_timeValid;
}
unsigned long NTPClient::getEpochTime() {
return this->_timeOffset + // User offset return this->_timeOffset + // User offset
this->_currentEpoc + // Epoc returned by the NTP server this->_currentEpoc + // Epoc returned by the NTP server
((millis() - this->_lastUpdate) / 1000); // Time since last update ((millis() - this->_lastUpdate + (_currentFraction / FRACTIONSPERMILLI)) / 1000); // Time since last update
} }
int NTPClient::getDay() const { unsigned long long NTPClient::getEpochMillis() {
unsigned long long epoch;
epoch = this->_timeOffset; // user offset
epoch += _currentEpoc; // last time returned via server
epoch *= 1000; // convert to millis
epoch += _currentFraction / FRACTIONSPERMILLI; // add the fraction from the server
epoch += millis() - this->_lastUpdate; // add the millis that have passed since the last update
return epoch;
}
int NTPClient::getDay() {
return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday
} }
int NTPClient::getHours() const { int NTPClient::getHours() {
return ((this->getEpochTime() % 86400L) / 3600); return ((this->getEpochTime() % 86400L) / 3600);
} }
int NTPClient::getMinutes() const { int NTPClient::getMinutes() {
return ((this->getEpochTime() % 3600) / 60); return ((this->getEpochTime() % 3600) / 60);
} }
int NTPClient::getSeconds() const { int NTPClient::getSeconds() {
return (this->getEpochTime() % 60); return (this->getEpochTime() % 60);
} }
boolean NTPClient::getTimeValid() const {
return (this->_timeValid);
}
String NTPClient::getFormattedTime() const { String NTPClient::getFormattedTime() {
unsigned long rawTime = this->getEpochTime(); unsigned long rawTime = this->getEpochTime();
unsigned long hours = (rawTime % 86400L) / 3600; unsigned long hours = (rawTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours); String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
@ -157,12 +206,16 @@ void NTPClient::setTimeOffset(int timeOffset) {
this->_timeOffset = timeOffset; this->_timeOffset = timeOffset;
} }
void NTPClient::setUpdateInterval(unsigned long updateInterval) { void NTPClient::setUpdateInterval(int updateInterval) {
this->_updateInterval = updateInterval; this->_updateInterval = updateInterval;
} }
void NTPClient::setPoolServerName(const char* poolServerName) { void NTPClient::setRetryInterval(int retryInterval) {
this->_poolServerName = poolServerName; _retryInterval = retryInterval;
}
void NTPClient::setUpdateCallback(NTPUpdateCallbackFunction f) {
_updateCallback = f;
} }
void NTPClient::sendNTPPacket() { void NTPClient::sendNTPPacket() {
@ -185,4 +238,7 @@ void NTPClient::sendNTPPacket() {
this->_udp->beginPacket(this->_poolServerName, 123); //NTP requests are to port 123 this->_udp->beginPacket(this->_poolServerName, 123); //NTP requests are to port 123
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE); this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
this->_udp->endPacket(); this->_udp->endPacket();
this->_lastRequest = millis();
} }