Skip to content

Commit

Permalink
New event structure
Browse files Browse the repository at this point in the history
  • Loading branch information
gmag11 committed Nov 26, 2020
1 parent 29b8b2a commit d17f531
Show file tree
Hide file tree
Showing 7 changed files with 159 additions and 55 deletions.
49 changes: 31 additions & 18 deletions examples/advancedExample/advancedExample.ino
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ const PROGMEM char* ntpServer = "pool.ntp.org";
bool wifiFirstConnected = false;

boolean syncEventTriggered = false; // True if a time even has been triggered
NTPSyncEvent_t ntpEvent; // Last triggered event
NTPEvent_t ntpEvent; // Last triggered event
double offset;
double timedelay;

Expand Down Expand Up @@ -77,21 +77,36 @@ void onWifiEvent (WiFiEvent_t event) {
}
}

void processSyncEvent (NTPSyncEvent_t ntpEvent, double offset, double tdelay) {
if (ntpEvent < 0) {
Serial.printf ("Time Sync error %d:", ntpEvent);
if (ntpEvent == noResponse) {
Serial.println ("NTP server not reachable");
} else if (ntpEvent == invalidAddress) {
Serial.println ("Invalid NTP server address");
void processSyncEvent (NTPEvent_t ntpEvent) {
Serial.print ("[NTP-event] ");
if (ntpEvent.event < 0) {
Serial.printf ("Time Sync error %d: ", ntpEvent.event);
if (ntpEvent.event == noResponse) {
Serial.printf ("NTP server not reachable: %s",
ntpEvent.info.serverAddress.toString ().c_str ());
} else if (ntpEvent.event == invalidAddress) {
Serial.printf ("Invalid NTP server address: %s",
ntpEvent.info.serverAddress.toString ().c_str ());
}
} else if (!ntpEvent) {
Serial.printf ("Got NTP time: %s. Offset: %0.3f ms. Delay: %0.3f ms\n",
NTP.getTimeDateString (NTP.getLastNTPSyncUs ()),
offset, timedelay);
} else {
Serial.println ("NTP request Sent");
if (!ntpEvent.event) {
Serial.printf ("Got NTP time: %s from %s:%u. Offset: %0.3f ms. Delay: %0.3f ms",
NTP.getTimeDateString (NTP.getLastNTPSyncUs ()),
ntpEvent.info.serverAddress.toString ().c_str (),
ntpEvent.info.port,
ntpEvent.info.offset * 1000,
ntpEvent.info.delay * 1000);
} else if (ntpEvent.event == requestSent) {
Serial.printf ("NTP request Sent to %s:%u",
ntpEvent.info.serverAddress.toString ().c_str (),
ntpEvent.info.port);
} else if (ntpEvent.event == partlySync) {
Serial.printf ("Partial sync %s Offset %0.3f",
NTP.getTimeDateString (NTP.getLastNTPSyncUs ()),
ntpEvent.info.offset * 1000);
}
}
Serial.println ();
}


Expand All @@ -104,11 +119,9 @@ void setup() {
pinMode (ONBOARDLED, OUTPUT); // Onboard LED
digitalWrite (ONBOARDLED, HIGH); // Switch off LED

NTP.onNTPSyncEvent ([] (NTPSyncEvent_t event, double toffset, double tdelay) {
NTP.onNTPSyncEvent ([] (NTPEvent_t event) {
ntpEvent = event;
syncEventTriggered = true;
offset = toffset * 1000;
timedelay = tdelay * 1000;
});
WiFi.onEvent (onWifiEvent);
}
Expand All @@ -120,13 +133,13 @@ void loop() {
if (wifiFirstConnected) {
wifiFirstConnected = false;
NTP.setTimeZone (TZ_Europe_Madrid);
NTP.setInterval (30);
NTP.setInterval (600);
NTP.setNTPTimeout (NTP_TIMEOUT);
NTP.begin (ntpServer);
}

if (syncEventTriggered) {
processSyncEvent (ntpEvent, offset, timedelay);
processSyncEvent (ntpEvent);
syncEventTriggered = false;
}

Expand Down
1 change: 0 additions & 1 deletion examples/basicExample/basicExample.ino
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
const PROGMEM char* ntpServer = "pool.ntp.org";

boolean syncEventTriggered = false; // True if a time even has been triggered
NTPSyncEvent_t ntpEvent; // Last triggered event

void setup() {
Serial.begin (115200);
Expand Down
5 changes: 3 additions & 2 deletions examples/basicExample/platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,16 @@

[platformio]
src_dir = .
lib_dir = ../..

[debug]
debug = ;-D DEBUG_NTPCLIENT

[env]
upload_speed = 921600
monitor_speed = 115200
lib_deps =
ESPNtpClient
;lib_deps =
; ESPNtpClient

[env:esp32]
platform = espressif32
Expand Down
7 changes: 7 additions & 0 deletions platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -19,16 +19,23 @@ debug = ;-D DEBUG_NTPCLIENT
upload_speed = 921600
monitor_speed = 115200
framework = arduino
monitor_filters = time

[esp32_common]
platform = espressif32
board = esp32dev
build_flags = -std=c++11 ${debug.debug}
monitor_filters =
${env.monitor_filters}
esp32_exception_decoder

[esp8266_common]
platform = espressif8266
board = esp12e
build_flags = -std=c++11 -D PIO_FRAMEWORK_ARDUINO_ESPRESSIF_SDK22x_191122 ${debug.debug}
monitor_filters =
${env.monitor_filters}
esp8266_exception_decoder

[env:advanced_esp32]
extends = esp32_common
Expand Down
105 changes: 82 additions & 23 deletions src/ESPNtpClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,8 +175,15 @@ void NTPClient::processPacket (struct pbuf* packet) {
// actualInterval = shortInterval;
// DEBUGLOG ("Set interval to = %d", actualInterval);
// DEBUGLOG ("Status set to UNSYNCD");
if (onSyncEvent)
onSyncEvent (responseError, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = responseError;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
event.info.offset = 0;
event.info.delay = 0;
onSyncEvent (event);
}
return;
}

Expand All @@ -185,12 +192,18 @@ void NTPClient::processPacket (struct pbuf* packet) {
decodeNtpMessage ((uint8_t*)packet->payload, packet->len, &ntpPacket);
timeval tvOffset = calculateOffset (&ntpPacket);
if (tvOffset.tv_sec == 0 && abs (tvOffset.tv_usec) < 1000) { // Less than 1 ms
DEBUGLOG ("Too low offset %0.3f ms", ((float)tvOffset.tv_sec+(float)tvOffset.tv_usec/1000000.0)*1000);
DEBUGLOG ("Offset %0.3f ms is under threshold. Not updating", ((float)tvOffset.tv_sec + (float)tvOffset.tv_usec / 1000000.0) * 1000);
} else {
if (!adjustOffset (&tvOffset)) {
DEBUGLOG ("Error applying offset");
if (onSyncEvent)
onSyncEvent (syncError, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = syncError;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
event.info.offset = ((float)tvOffset.tv_sec + (float)tvOffset.tv_usec / 1000000.0) * 1000.0;
onSyncEvent (event);
}
}
offsetApplied = true;

Expand All @@ -209,14 +222,24 @@ void NTPClient::processPacket (struct pbuf* packet) {
} else {
actualInterval = longInterval;
}
DEBUGLOG ("Iinterval set to = %d", actualInterval);
DEBUGLOG ("Interval set to = %d", actualInterval);
DEBUGLOG ("Sync frequency set low");
DEBUGLOG ("Successful NTP sync at %s", getTimeDateString (getLastNTPSync ()));
if (!firstSync.tv_sec) {
firstSync = lastSyncd;
}
if (offsetApplied && onSyncEvent) {
onSyncEvent (timeSyncd, offset, delay);
NTPEvent_t event;
if (status == partialSync){
event.event = partlySync;
} else {
event.event = timeSyncd;
}
event.info.offset = offset;
event.info.delay = delay;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
// const int sizeStr = 200;
// char strBuffer[sizeStr];
Expand Down Expand Up @@ -316,16 +339,27 @@ void NTPClient::getTime () {
result = WiFi.hostByName (getNtpServerName (), ntpServerIPAddress);
if (!result) {
DEBUGLOG ("HostByName error %d", (int)result);
if (onSyncEvent)
onSyncEvent (invalidAddress, 0, 0);
return;

if (onSyncEvent) {
NTPEvent_t event;
event.event = invalidAddress;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;

onSyncEvent (event);
}
}
if (ntpServerIPAddress == INADDR_NONE) {
DEBUGLOG ("IP address unset. Aborting");
actualInterval = shortInterval;
DEBUGLOG ("Set interval to = %d", actualInterval);
if (onSyncEvent)
onSyncEvent (invalidAddress, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = invalidAddress;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
return;
}

Expand All @@ -340,14 +374,24 @@ void NTPClient::getTime () {
result = udp_connect (udp, &ntpAddr, DEFAULT_NTP_PORT);
if (result == ERR_USE) {
DEBUGLOG ("Port already used");
if (onSyncEvent)
onSyncEvent (invalidPort, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = invalidPort;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
//return;
}
if (result == ERR_RTE) {
DEBUGLOG ("Port already used");
if (onSyncEvent)
onSyncEvent (invalidAddress, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = invalidAddress;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
//return;
}

Expand All @@ -362,12 +406,22 @@ void NTPClient::getTime () {
DEBUGLOG ("NTP request error");
status = prevStatus;
DEBUGLOG ("Status recovered due to UDP send error");
if (onSyncEvent)
onSyncEvent (errorSending, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = errorSending;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
return;
}
if (onSyncEvent)
onSyncEvent (requestSent, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = requestSent;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
udp_disconnect (udp);

}
Expand Down Expand Up @@ -435,14 +489,19 @@ void ICACHE_RAM_ATTR NTPClient::processRequestTimeout () {
//timer1_disable ();
responseTimer.detach ();
DEBUGLOG ("NTP response Timeout");
if (onSyncEvent)
onSyncEvent (noResponse, 0, 0);
if (onSyncEvent) {
NTPEvent_t event;
event.event = noResponse;
event.info.serverAddress = ntpServerIPAddress;
event.info.port = DEFAULT_NTP_PORT;
onSyncEvent (event);
}
// if (status==syncd) {
// actualInterval = longInterval;
// } else {
// actualInterval = shortInterval;
// }
DEBUGLOG ("Set interval to = %d", actualInterval);
//DEBUGLOG ("Set interval to = %d", actualInterval);
}

bool NTPClient::setNtpServerName (const char* serverName) {
Expand Down
13 changes: 2 additions & 11 deletions src/ESPNtpClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,16 +72,7 @@ constexpr auto SECS_YR_2000 = ((time_t)(946684800UL)); // the time at the start
#endif
#include <Ticker.h>

typedef enum NTPSyncEvent {
timeSyncd = 0, // Time successfully got from NTP server
noResponse = -1, // No response from server
invalidAddress= -2, // Address not reachable
invalidPort = -3, // Port already used
requestSent = 1, // NTP request sent, waiting for response
errorSending = -4, // An error happened while sending the request
responseError = -5, // Wrong response received
syncError = -6 // Error adjusting time
} NTPSyncEvent_t;
#include "NTPEventTypes.h"

typedef enum NTPStatus {
syncd = 0, // Time synchronized correctly
Expand Down Expand Up @@ -111,7 +102,7 @@ typedef struct {
timeval transmit;
} NTPPacket_t;

typedef std::function<void (NTPSyncEvent_t, double, double)> onSyncEvent_t;
typedef std::function<void (NTPEvent_t)> onSyncEvent_t;

static char strBuffer[35];

Expand Down
34 changes: 34 additions & 0 deletions src/NTPEventTypes.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#ifndef _NtpEventTypes_h
#define _NtpEventTypes_h

#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif

typedef enum {
timeSyncd = 0, // Time successfully got from NTP server
noResponse = -1, // No response from server
invalidAddress = -2, // Address not reachable
invalidPort = -3, // Port already used
requestSent = 1, // NTP request sent, waiting for response
partlySync = 2, // Successful sync but offset was over threshold
errorSending = -4, // An error happened while sending the request
responseError = -5, // Wrong response received
syncError = -6 // Error adjusting time
} NTPSyncEventType_t;

typedef struct {
double offset = 0.0;
double delay = 0.0;
IPAddress serverAddress;
unsigned int port = 0;
} NTPSyncEventInfo_t;

typedef struct {
NTPSyncEventType_t event;
NTPSyncEventInfo_t info;
} NTPEvent_t;

#endif // _NtpEventTypes_h

0 comments on commit d17f531

Please sign in to comment.