Skip to content

Non blocking update needed for "super-loop" enjoyers #206

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

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
37 changes: 37 additions & 0 deletions NTPClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -126,10 +126,47 @@ bool NTPClient::update() {
return false; // return false if update does not occur
}

int NTPClient::asyncUpdate() {
if ((millis() - this->_sendTime >= this->_updateInterval) // Update after _updateInterval
|| this->_sendTime == 0) { // Update if there was no update yet.
_sendTime = millis();
if (!this->_udpSetup || this->_port != NTP_DEFAULT_LOCAL_PORT) this->begin(this->_port); // setup the UDP client if needed
this->sendNTPPacket();

int code = 2;
if (_needUpdate) code = -1; // timeout
_needUpdate = true;
return code;
}

if (_needUpdate) {
int cb = this->_udp->parsePacket();
if (cb == 0) return 2;
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;
this->_lastUpdate = millis();
_needUpdate = false;
return 0;
}

return 1; // return false if update does not occur
}

bool NTPClient::isTimeSet() const {
return (this->_lastUpdate != 0); // returns true if the time has been set, else false
}

long long NTPClient::getEpochTimeMillis() const {
return this->_currentEpoc * 1000LL + millis() - this->_lastUpdate;
}

unsigned long NTPClient::getEpochTime() const {
return this->_timeOffset + // User offset
this->_currentEpoc + // Epoch returned by the NTP server
Expand Down
16 changes: 16 additions & 0 deletions NTPClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ class NTPClient {

unsigned long _updateInterval = 60000; // In ms

bool _needUpdate = true;
unsigned long _sendTime = 0;
unsigned long _currentEpoc = 0; // In s
unsigned long _lastUpdate = 0; // In ms

Expand Down Expand Up @@ -74,6 +76,14 @@ class NTPClient {
*/
bool forceUpdate();

/**
* Alternatevly this can be called instead of update() in the main loop of your application.
* AsyncUpdate from the NTP Server is made every _updateInterval milliseconds.
*
* @return 0 on success, -1 on failure, 1 if no update is needed, 2 if update is in progress
*/
int asyncUpdate();

/**
* This allows to check if the NTPClient successfully received a NTP packet and set the time.
*
Expand Down Expand Up @@ -107,6 +117,12 @@ class NTPClient {
*/
unsigned long getEpochTime() const;


/**
* @return time in milliseconds since Jan. 1, 1970 (UTC+0)
*/
long long getEpochTimeMillis() const;

/**
* Stops the underlying UDP client
*/
Expand Down
50 changes: 50 additions & 0 deletions examples/AsyncUpdate/AsyncUpdate.ino
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
#include <NTPClient.h>
// change next line to use with another board/shield
#include <ESP8266WiFi.h>
//#include <WiFi.h> // for WiFi shield
//#include <WiFi101.h> // for WiFi 101 shield or MKR1000
#include <WiFiUdp.h>

#define SSID "<your-ssid>"
#define PASSWORD "<your-password>"

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "0.asia.pool.ntp.org", 0, 1500);

void setup(){
Serial.begin(115200);

WiFi.begin(SSID, PASSWORD);

while ( WiFi.status() != WL_CONNECTED ) {
delay ( 500 );
Serial.print ( "." );
}

timeClient.begin();
}

void loop() {
long int loopMillis = millis();
static int prevRes = 0;
// with update() method loop will be blocked until time is updated
// timeClient.update();
int res = timeClient.asyncUpdate();

if (res != prevRes) {
Serial.printf("Result: %d\n", res);
prevRes = res;
}

static long int lm = 0;

if (millis() - lm > 1000) {
lm = millis();
Serial.printf("%s.%d\n", timeClient.getFormattedTime().c_str(), int(timeClient.getEpochTimeMillis()%1000));
}

long int dd = millis() - loopMillis;
if (dd > 10) {
Serial.printf("Loop took %d ms...\n", dd);
}
}
2 changes: 1 addition & 1 deletion library.properties
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
name=NTPClient
version=3.2.1
version=3.3.1
author=Fabrice Weinberg
maintainer=Fabrice Weinberg <[email protected]>
sentence=An NTPClient to connect to a time server
Expand Down
Loading