From 81815084cfbfccf0057f10e17baf97127c66f098 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Tue, 19 Sep 2017 18:03:35 +0200 Subject: [PATCH 01/30] Start code integration This branch is going to integrate both main platforms, ESP8266 and AVR into the same code --- .../NTPClientESP8266/AvrNtpClientLib.cpp | 0 examples/NTPClientESP8266/NTPClientESP8266.ino | 2 +- .../NTPClientESP8266/NTPClientLib.cpp | 0 {src => examples/NTPClientESP8266}/NtpClientLib.h | 0 4 files changed, 1 insertion(+), 1 deletion(-) rename src/AvrNTPClient.cpp => examples/NTPClientESP8266/AvrNtpClientLib.cpp (100%) rename src/ESPNTPClient.cpp => examples/NTPClientESP8266/NTPClientLib.cpp (100%) rename {src => examples/NTPClientESP8266}/NtpClientLib.h (100%) diff --git a/src/AvrNTPClient.cpp b/examples/NTPClientESP8266/AvrNtpClientLib.cpp similarity index 100% rename from src/AvrNTPClient.cpp rename to examples/NTPClientESP8266/AvrNtpClientLib.cpp diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index 30091cf..c907d30 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -35,7 +35,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G #include #include "WifiConfig.h" -#include +#include "NtpClientLib.h" #include #ifndef WIFI_CONFIG_H diff --git a/src/ESPNTPClient.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp similarity index 100% rename from src/ESPNTPClient.cpp rename to examples/NTPClientESP8266/NTPClientLib.cpp diff --git a/src/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h similarity index 100% rename from src/NtpClientLib.h rename to examples/NTPClientESP8266/NtpClientLib.h From 06572b45fd63ba23abb386d003eb9f1e70604e78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Tue, 19 Sep 2017 18:57:20 +0200 Subject: [PATCH 02/30] Code rewrite --- examples/NTPClientESP8266/NTPClientLib.cpp | 416 +++++------------- examples/NTPClientESP8266/NtpClientLib.h | 31 +- .../AvrNtpClientLib.cpp | 0 src/NTPClientLib.cpp | 397 +++++++++++++++++ 4 files changed, 521 insertions(+), 323 deletions(-) rename {examples/NTPClientESP8266 => src}/AvrNtpClientLib.cpp (100%) create mode 100644 src/NTPClientLib.cpp diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index e83800a..76a4574 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -32,7 +32,6 @@ or implied, of German Martin #ifdef ARDUINO_ARCH_ESP8266 #include "NtpClientLib.h" -#include #define DBG_PORT Serial @@ -47,52 +46,140 @@ NTPClient NTP; NTPClient::NTPClient() { + udp = new WiFiUDP (); } bool NTPClient::setNtpServerName(String ntpServerName, int idx) { - char * buffer = (char *)malloc((ntpServerName.length()+1) * sizeof(char)); - if ((idx >= 0) && (idx <= 2)) { - sntp_stop(); - ntpServerName.toCharArray(buffer, ntpServerName.length()+1); - sntp_setservername(idx, buffer); - DEBUGLOG("NTP server %d set to: %s \r\n", idx, buffer); - sntp_init(); - return true; - } - return false; + char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char)); + if (!name) + return false; + ntpServerName.toCharArray (name, ntpServerName.length () + 1); + DEBUGLOG ("NTP server set to %s\n", name); + free (_ntpServerName); + _ntpServerName = name; + return true; +} + +bool NTPClient::setNtpServerName (char* ntpServerName, int idx) { + char *name = ntpServerName; + if (name == NULL) + return false; + DEBUGLOG ("NTP server set to %s\n", name); + free (_ntpServerName); + _ntpServerName = name; + return true; } String NTPClient::getNtpServerName(int idx) { - if ((idx >= 0) && (idx <= 2)) { - return String(sntp_getservername(idx)); - } + if ((idx >= 0) && (idx <= 0)) { + return String (_ntpServerName); + } return ""; } +char* NTPClient::getNtpServerNamePtr (int idx) { + if ((idx >= 0) && (idx <= 0)) { + return _ntpServerName; + } + return ""; +} + bool NTPClient::setTimeZone(int timeZone) { - //if ((timeZone >= -11) && (timeZone <= 13)) { + if ((timeZone >= -11) && (timeZone <= 13)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; setTime(now() + timeDiff * 3600); - sntp_stop(); - bool result = sntp_set_timezone(timeZone); - sntp_init(); - setTime(getTime()); - DEBUGLOG("NTP time zone set to: %d, result: %s\r\n", timeZone, result?"OK":"error"); - return result; - //return true; - //} - //return false; + setTime (getTime ()); + DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); + return true; + } + return false; +} + +boolean sendNTPpacket (IPAddress &address, UDP *udp) { + char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message + + // set all bytes in the buffer to 0 + memset (ntpPacketBuffer, 0, NTP_PACKET_SIZE); + // Initialize values needed to form NTP request + // (see URL above for details on the packets) + ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode + ntpPacketBuffer[1] = 0; // Stratum, or type of clock + ntpPacketBuffer[2] = 6; // Polling Interval + ntpPacketBuffer[3] = 0xEC; // Peer Clock Precision + // 8 bytes of zero for Root Delay & Root Dispersion + ntpPacketBuffer[12] = 49; + ntpPacketBuffer[13] = 0x4E; + ntpPacketBuffer[14] = 49; + ntpPacketBuffer[15] = 52; + // all NTP fields have been given values, now + // you can send a packet requesting a timestamp: + udp->beginPacket (address, 123); //NTP requests are to port 123 + udp->write(ntpPacketBuffer, NTP_PACKET_SIZE); + udp->endPacket (); + return true; +} + +time_t NTPClient::getTime () { + //DNSClient dns; + //WiFiUDP *udpClient = new WiFiUDP(*udp); + IPAddress timeServerIP; //NTP server IP address + char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store response message + + + DEBUGLOG ("Starting UDP"); + udp->begin (DEFAULT_NTP_PORT); + DEBUGLOG ("Remote port: %d\n",udp->remotePort()); + while (udp->parsePacket () > 0); // discard any previously received packets + /*dns.begin(WiFi.dnsServerIP()); + uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP); + DEBUGLOG(F("NTP Server hostname: ")); + DEBUGLOGCR(NTP.getNtpServerName()); + DEBUGLOG(F("NTP Server IP address: ")); + DEBUGLOGCR(timeServerIP); + DEBUGLOG(F("Result code: ")); + DEBUGLOG(dnsResult); + DEBUGLOG(" "); + DEBUGLOGCR(F("-- IP Connected. Waiting for sync")); + DEBUGLOGCR(F("-- Transmit NTP Request"));*/ + + //if (dnsResult == 1) { //If DNS lookup resulted ok + sendNTPpacket (NTP.getNtpServerName ().c_str (), udp); + uint32_t beginWait = millis (); + while (millis () - beginWait < 1500) { + int size = udp->parsePacket (); + if (size >= NTP_PACKET_SIZE) { + DEBUGLOG ("-- Receive NTP Response\n"); + udp->read (ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer + time_t timeValue = NTP.decodeNtpMessage (ntpPacketBuffer); + setSyncInterval (NTP.getLongInterval ()); + NTP.getFirstSync (); // Set firstSync value if not set before + DEBUGLOG ("Sync frequency set low\n"); + udp->stop (); + NTP.setLastNTPSync (timeValue); + DEBUGLOG ("Succeccful NTP sync at %s", NTP.getTimeDateString (NTP.getLastNTPSync ()).c_str()); + + if (onSyncEvent) + onSyncEvent (timeSyncd); + return timeValue; + } + } + DEBUGLOGCR (F ("-- No NTP Response :-(")); + udp.stop (); + setSyncInterval (NTP.getShortInterval ()); // Retry connection more often + if (onSyncEvent) + onSyncEvent (noResponse); + return 0; // return 0 if unable to get the time } int NTPClient::getTimeZone() { - return sntp_get_timezone(); + return _timeZone; } /*void NTPClient::setLastNTPSync(time_t moment) { @@ -103,284 +190,5 @@ time_t NTPClient::s_getTime() { return NTP.getTime(); } -time_t NTPClient::getTime() -{ - DEBUGLOG("-- NTP Server hostname: %s\r\n", sntp_getservername(0)); - if (WiFi.isConnected()) { - DEBUGLOG("-- Transmit NTP Request\r\n"); - uint32 secsSince1970 = sntp_get_current_timestamp(); - NTP.getUptime(); // Keep uptime updated to avoid overflow if not called - if (secsSince1970) { - setSyncInterval(NTP.getInterval()); // Normal refresh frequency - DEBUGLOG("Sync frequency set low\r\n"); - if (_daylight) { - if (summertime(year(secsSince1970), month(secsSince1970), day(secsSince1970), hour(secsSince1970), getTimeZone())) { - secsSince1970 += SECS_PER_HOUR; - DEBUGLOG("Summer Time\r\n"); - } - else { - DEBUGLOG("Winter Time\r\n"); - } - - } - else { - DEBUGLOG("No daylight\r\n"); - - } - getFirstSync(); - _lastSyncd = secsSince1970; - if (!_firstSync) { // first sync is not set - _firstSync = secsSince1970; - DEBUGLOG("First sync! %s\r\n", getTimeDateString(getFirstSync()).c_str()); - } - DEBUGLOG("Succeccful NTP sync at %s\r\n", getTimeDateString(getLastNTPSync()).c_str()); - } - else { - DEBUGLOG("-- NTP error :-(\r\n"); - setSyncInterval(getShortInterval()); // Fast refresh frequency, until successful sync - if (onSyncEvent) - onSyncEvent(noResponse); - if (!_firstSync) // first sync is not set - return 0; - else - return now(); - } - - if (onSyncEvent) - onSyncEvent(timeSyncd); - return secsSince1970; - } - else { - DEBUGLOG("-- NTP Error. WiFi not connected.\r\n"); - if (onSyncEvent) - onSyncEvent(noResponse); - if (!_firstSync) // first sync is not set - return 0; - else - return now(); - } -} - -bool NTPClient::begin(String ntpServerName, int timeZone, bool daylight) -{ - if (!setNtpServerName(ntpServerName)) { - return false; - } - if (!setTimeZone(timeZone)) { - return false; - } - _timeZone = timeZone; - sntp_init(); - setDayLight(daylight); - _lastSyncd = 0; - - if (!setInterval(DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { - return false; - } - DEBUGLOG("Time sync started\r\n"); - - setSyncInterval(getShortInterval()); - setSyncProvider(s_getTime); - - return true; -} - -bool NTPClient::stop() { - setSyncProvider(NULL); - DEBUGLOG("Time sync disabled\r\n"); - sntp_stop(); - return true; -} - -bool NTPClient::setInterval(int interval) -{ - if (interval >= 10) { - if (_longInterval != interval) { - _longInterval = interval; - DEBUGLOG("Long sync interval set to %d\r\n", interval); - if (timeStatus() == timeSet) - setSyncInterval(interval); - } - return true; - } - DEBUGLOG("Error setting interval %d\r\n", interval); - - return false; -} - -bool NTPClient::setInterval(int shortInterval, int longInterval) { - if (shortInterval >= 5 && longInterval >= 10) { - _shortInterval = shortInterval; - _longInterval = longInterval; - if (timeStatus() != timeSet) { - setSyncInterval(shortInterval); - } - else { - setSyncInterval(longInterval); - } - DEBUGLOG("Short sync interval set to %d\r\n", shortInterval); - DEBUGLOG("Long sync interval set to %d\r\n", longInterval); - return true; - } - DEBUGLOG("Error setting interval. Short: %d Long: %d\r\n", shortInterval, longInterval); - return false; -} - -int NTPClient::getInterval() -{ - return _longInterval; -} - -int NTPClient::getShortInterval() -{ - return _shortInterval; -} - -void NTPClient::setDayLight(bool daylight) -{ - _daylight = daylight; - DEBUGLOG("--Set daylight %s\r\n", daylight? "ON" : "OFF"); - setTime(getTime()); -} - -bool NTPClient::getDayLight() -{ - return _daylight; -} - -String NTPClient::getTimeStr(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += printDigits(hour(moment)); - timeStr += ":"; - timeStr += printDigits(minute(moment)); - timeStr += ":"; - timeStr += printDigits(second(moment)); - - return timeStr; - //} - //else return "Time not set"; -} - -String NTPClient::getTimeStr() { - return getTimeStr(now()); -} - -String NTPClient::getDateStr(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - - timeStr += printDigits(day(moment)); - timeStr += "/"; - timeStr += printDigits(month(moment)); - timeStr += "/"; - timeStr += String(year(moment)); - - return timeStr; - //} - //else return "Date not set"; -} - -String NTPClient::getDateStr() { - return getDateStr(now()); -} - -String NTPClient::getTimeDateString(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += getTimeStr(moment); - timeStr += " "; - timeStr += getDateStr(moment); - - return timeStr; - //} - //else return "Time not set"; -} - -String NTPClient::getTimeDateString() { - return getTimeDateString(now()); -} - -String NTPClient::printDigits(int digits) { - // utility for digital clock display: prints preceding colon and leading 0 - String digStr = ""; - - if (digits < 10) - digStr += '0'; - digStr += String(digits); - - return digStr; -} - -bool NTPClient::summertime(int year, byte month, byte day, byte hour, byte tzHours) -// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) -{ - if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez - if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep - if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) - return true; - else - return false; -} - -time_t NTPClient::getLastBootTime() { - if (timeStatus() == timeSet) { - return (now() - getUptime()); - } - return 0; -} - -time_t NTPClient::getUptime() -{ - _uptime = _uptime + (millis() - _uptime); - return _uptime / 1000; -} - -time_t NTPClient::getFirstSync() -{ - if (!_firstSync) { - if (timeStatus() == timeSet) { - _firstSync = now() - getUptime(); - } - } - - return _firstSync; -} - -String NTPClient::getUptimeString() { - uint days; - uint8 hours; - uint8 minutes; - uint8 seconds; - - long uptime = getUptime(); - - seconds = uptime % SECS_PER_MIN; - uptime -= seconds; - minutes = (uptime % SECS_PER_HOUR)/ SECS_PER_MIN; - uptime -= minutes * SECS_PER_MIN; - hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; - uptime -= hours * SECS_PER_HOUR; - days = uptime / SECS_PER_DAY; - - String uptimeStr = ""; - char buffer[20]; - sprintf(buffer, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); - uptimeStr += buffer; - - return uptimeStr; -} - -time_t NTPClient::getLastNTPSync() { - return _lastSyncd; -} - -void NTPClient::onNTPSyncEvent(onSyncEvent_t handler) { - onSyncEvent = handler; -} - -boolean NTPClient::isSummerTimePeriod(time_t moment) { - return summertime(year(), month(), day(), hour(), getTimeZone()); -} #endif // ARDUINO_ARCH_ESP8266 \ No newline at end of file diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 9c5fa0a..047d247 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -38,7 +38,7 @@ or implied, of German Martin #ifndef _NtpClientLib_h #define _NtpClientLib_h -//#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port +#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port #ifdef ESP8266 extern "C" { @@ -46,6 +46,9 @@ extern "C" { #include "sntp.h" } #include +#include +#include +#include using namespace std; using namespace placeholders; #endif @@ -118,6 +121,8 @@ class NTPClient{ */ NTPClient(); + NTPClient (UDP* udp_conn); + /** * Starts time synchronization. * @param[in] NTP server name as String. @@ -135,6 +140,7 @@ class NTPClient{ * @param[out] True if everything went ok. */ bool setNtpServerName(String ntpServerName, int idx = 0); + bool setNtpServerName (char* ntpServerName, int idx = 0); /** * Gets NTP server name @@ -142,6 +148,7 @@ class NTPClient{ * @param[out] NTP server name. */ String getNtpServerName(int idx = 0); + char* getNtpServerNamePtr (int idx = 0); /** * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. @@ -150,20 +157,6 @@ class NTPClient{ */ time_t getTime(); #endif -#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 - /** - * Sets NTP server name. - * @param[in] New NTP server name. - * @param[out] True if everything went ok. - */ - bool setNtpServerName(String ntpServerName); - - /** - * Gets NTP server name - * @param[out] NTP server name. - */ - String getNtpServerName(); -#endif /** * Sets timezone. @@ -334,8 +327,9 @@ class NTPClient{ protected: + UDP *udp; bool _daylight; //Does this time zone have daylight saving? - int8_t _timeZone; //Keep track of set time zone offset + int8_t _timeZone = 0; //Keep track of set time zone offset int _shortInterval; //Interval to set periodic time sync until first synchronization. int _longInterval; //Interval to set periodic time sync time_t _lastSyncd = 0; //Stored time of last successful sync @@ -367,9 +361,8 @@ class NTPClient{ */ String printDigits(int digits); -#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 +//#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 - int _timeZone = 0; char* _ntpServerName; public: @@ -393,7 +386,7 @@ class NTPClient{ * @param[out] True if everything went ok. */ //bool sendNTPpacket(IPAddress &address); -#endif +//#endif }; extern NTPClient NTP; diff --git a/examples/NTPClientESP8266/AvrNtpClientLib.cpp b/src/AvrNtpClientLib.cpp similarity index 100% rename from examples/NTPClientESP8266/AvrNtpClientLib.cpp rename to src/AvrNtpClientLib.cpp diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp new file mode 100644 index 0000000..e1fea67 --- /dev/null +++ b/src/NTPClientLib.cpp @@ -0,0 +1,397 @@ +/* +Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are +permitted provided that the following conditions are met : + +1. Redistributions of source code must retain the above copyright notice, this list of +conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list +of conditions and the following disclaimer in the documentation and / or other materials +provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those of the +authors and should not be interpreted as representing official policies, either expressed +or implied, of German Martin +*/ +// +// +// + +#ifdef ARDUINO_ARCH_ESP8266 + +#include "NtpClientLib.h" + +#define DBG_PORT Serial + +#ifdef DEBUG_NTPCLIENT +#define DEBUGLOG(...) DBG_PORT.printf(__VA_ARGS__) +#else +#define DEBUGLOG(...) +#endif + + +NTPClient NTP; + +NTPClient::NTPClient() +{ + udp = new WiFiUDP (); +} + +bool NTPClient::setNtpServerName(String ntpServerName, int idx) +{ + char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char)); + if (name == NULL) + return false; + ntpServerName.toCharArray (name, ntpServerName.length () + 1); + DEBUGLOG ("NTP server set to %s\n", name); + free (_ntpServerName); + _ntpServerName = name; + return true; +} + +bool NTPClient::setNtpServerName (char* ntpServerName, int idx) { + char *name = ntpServerName; + if (name == NULL) + return false; + DEBUGLOG ("NTP server set to %s\n", name); + free (_ntpServerName); + _ntpServerName = name; + return true; +} + +String NTPClient::getNtpServerName(int idx) +{ + if ((idx >= 0) && (idx <= 0)) { + return String (_ntpServerName); + } + return ""; +} + +char* NTPClient::getNtpServerNamePtr (int idx) { + if ((idx >= 0) && (idx <= 0)) { + return _ntpServerName); + } + return ""; +} + +bool NTPClient::setTimeZone(int timeZone) +{ + if ((timeZone >= -11) && (timeZone <= 13)) { + // Temporarily set time to new time zone, before trying to synchronize + int8_t timeDiff = timeZone - _timeZone; + _timeZone = timeZone; + setTime(now() + timeDiff * 3600); + + setTime (getTime ()); + DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); + return true; + } + return false; +} + +int NTPClient::getTimeZone() +{ + return _timeZone; +} + +/*void NTPClient::setLastNTPSync(time_t moment) { + _lastSyncd = moment; +}*/ + +time_t NTPClient::s_getTime() { + return NTP.getTime(); +} + +time_t NTPClient::getTime() +{ + DEBUGLOG("-- NTP Server hostname: %s\r\n", sntp_getservername(0)); + if (WiFi.isConnected()) { + DEBUGLOG("-- Transmit NTP Request\r\n"); + uint32 secsSince1970 = sntp_get_current_timestamp(); + NTP.getUptime(); // Keep uptime updated to avoid overflow if not called + if (secsSince1970) { + setSyncInterval(NTP.getInterval()); // Normal refresh frequency + DEBUGLOG("Sync frequency set low\r\n"); + if (_daylight) { + if (summertime(year(secsSince1970), month(secsSince1970), day(secsSince1970), hour(secsSince1970), getTimeZone())) { + secsSince1970 += SECS_PER_HOUR; + DEBUGLOG("Summer Time\r\n"); + } + else { + DEBUGLOG("Winter Time\r\n"); + } + + } + else { + DEBUGLOG("No daylight\r\n"); + + } + getFirstSync(); + _lastSyncd = secsSince1970; + if (!_firstSync) { // first sync is not set + _firstSync = secsSince1970; + DEBUGLOG("First sync! %s\r\n", getTimeDateString(getFirstSync()).c_str()); + } + DEBUGLOG("Succeccful NTP sync at %s\r\n", getTimeDateString(getLastNTPSync()).c_str()); + } + else { + DEBUGLOG("-- NTP error :-(\r\n"); + setSyncInterval(getShortInterval()); // Fast refresh frequency, until successful sync + if (onSyncEvent) + onSyncEvent(noResponse); + if (!_firstSync) // first sync is not set + return 0; + else + return now(); + } + + if (onSyncEvent) + onSyncEvent(timeSyncd); + return secsSince1970; + } + else { + DEBUGLOG("-- NTP Error. WiFi not connected.\r\n"); + if (onSyncEvent) + onSyncEvent(noResponse); + if (!_firstSync) // first sync is not set + return 0; + else + return now(); + } +} + +bool NTPClient::begin(String ntpServerName, int timeZone, bool daylight) +{ + if (!setNtpServerName(ntpServerName)) { + return false; + } + if (!setTimeZone(timeZone)) { + return false; + } + _timeZone = timeZone; + sntp_init(); + setDayLight(daylight); + _lastSyncd = 0; + + if (!setInterval(DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { + return false; + } + DEBUGLOG("Time sync started\r\n"); + + setSyncInterval(getShortInterval()); + setSyncProvider(s_getTime); + + return true; +} + +bool NTPClient::stop() { + setSyncProvider(NULL); + DEBUGLOG("Time sync disabled\r\n"); + sntp_stop(); + return true; +} + +bool NTPClient::setInterval(int interval) +{ + if (interval >= 10) { + if (_longInterval != interval) { + _longInterval = interval; + DEBUGLOG("Long sync interval set to %d\r\n", interval); + if (timeStatus() == timeSet) + setSyncInterval(interval); + } + return true; + } + DEBUGLOG("Error setting interval %d\r\n", interval); + + return false; +} + +bool NTPClient::setInterval(int shortInterval, int longInterval) { + if (shortInterval >= 5 && longInterval >= 10) { + _shortInterval = shortInterval; + _longInterval = longInterval; + if (timeStatus() != timeSet) { + setSyncInterval(shortInterval); + } + else { + setSyncInterval(longInterval); + } + DEBUGLOG("Short sync interval set to %d\r\n", shortInterval); + DEBUGLOG("Long sync interval set to %d\r\n", longInterval); + return true; + } + DEBUGLOG("Error setting interval. Short: %d Long: %d\r\n", shortInterval, longInterval); + return false; +} + +int NTPClient::getInterval() +{ + return _longInterval; +} + +int NTPClient::getShortInterval() +{ + return _shortInterval; +} + +void NTPClient::setDayLight(bool daylight) +{ + _daylight = daylight; + DEBUGLOG("--Set daylight %s\r\n", daylight? "ON" : "OFF"); + setTime(getTime()); +} + +bool NTPClient::getDayLight() +{ + return _daylight; +} + +String NTPClient::getTimeStr(time_t moment) { + //if ((timeStatus() != timeNotSet) || (moment != 0)) { + String timeStr = ""; + timeStr += printDigits(hour(moment)); + timeStr += ":"; + timeStr += printDigits(minute(moment)); + timeStr += ":"; + timeStr += printDigits(second(moment)); + + return timeStr; + //} + //else return "Time not set"; +} + +String NTPClient::getTimeStr() { + return getTimeStr(now()); +} + +String NTPClient::getDateStr(time_t moment) { + //if ((timeStatus() != timeNotSet) || (moment != 0)) { + String timeStr = ""; + + timeStr += printDigits(day(moment)); + timeStr += "/"; + timeStr += printDigits(month(moment)); + timeStr += "/"; + timeStr += String(year(moment)); + + return timeStr; + //} + //else return "Date not set"; +} + +String NTPClient::getDateStr() { + return getDateStr(now()); +} + +String NTPClient::getTimeDateString(time_t moment) { + //if ((timeStatus() != timeNotSet) || (moment != 0)) { + String timeStr = ""; + timeStr += getTimeStr(moment); + timeStr += " "; + timeStr += getDateStr(moment); + + return timeStr; + //} + //else return "Time not set"; +} + +String NTPClient::getTimeDateString() { + return getTimeDateString(now()); +} + +String NTPClient::printDigits(int digits) { + // utility for digital clock display: prints preceding colon and leading 0 + String digStr = ""; + + if (digits < 10) + digStr += '0'; + digStr += String(digits); + + return digStr; +} + +bool NTPClient::summertime(int year, byte month, byte day, byte hour, byte tzHours) +// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) +{ + if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez + if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep + if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) + return true; + else + return false; +} + +time_t NTPClient::getLastBootTime() { + if (timeStatus() == timeSet) { + return (now() - getUptime()); + } + return 0; +} + +time_t NTPClient::getUptime() +{ + _uptime = _uptime + (millis() - _uptime); + return _uptime / 1000; +} + +time_t NTPClient::getFirstSync() +{ + if (!_firstSync) { + if (timeStatus() == timeSet) { + _firstSync = now() - getUptime(); + } + } + + return _firstSync; +} + +String NTPClient::getUptimeString() { + uint days; + uint8 hours; + uint8 minutes; + uint8 seconds; + + long uptime = getUptime(); + + seconds = uptime % SECS_PER_MIN; + uptime -= seconds; + minutes = (uptime % SECS_PER_HOUR)/ SECS_PER_MIN; + uptime -= minutes * SECS_PER_MIN; + hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; + uptime -= hours * SECS_PER_HOUR; + days = uptime / SECS_PER_DAY; + + String uptimeStr = ""; + char buffer[20]; + sprintf(buffer, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); + uptimeStr += buffer; + + return uptimeStr; +} + +time_t NTPClient::getLastNTPSync() { + return _lastSyncd; +} + +void NTPClient::onNTPSyncEvent(onSyncEvent_t handler) { + onSyncEvent = handler; +} + +boolean NTPClient::isSummerTimePeriod(time_t moment) { + return summertime(year(), month(), day(), hour(), getTimeZone()); +} + +#endif // ARDUINO_ARCH_ESP8266 \ No newline at end of file From 0971e794dfa397e1f4f67511184dc3f4d34d22e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Tue, 19 Sep 2017 18:58:35 +0200 Subject: [PATCH 03/30] Old code restore --- src/{AvrNtpClientLib.cpp => AvrNTPClient.cpp} | 0 src/{NTPClientLib.cpp => ESPNTPClient.cpp} | 61 ++++++++----------- 2 files changed, 25 insertions(+), 36 deletions(-) rename src/{AvrNtpClientLib.cpp => AvrNTPClient.cpp} (100%) rename src/{NTPClientLib.cpp => ESPNTPClient.cpp} (90%) diff --git a/src/AvrNtpClientLib.cpp b/src/AvrNTPClient.cpp similarity index 100% rename from src/AvrNtpClientLib.cpp rename to src/AvrNTPClient.cpp diff --git a/src/NTPClientLib.cpp b/src/ESPNTPClient.cpp similarity index 90% rename from src/NTPClientLib.cpp rename to src/ESPNTPClient.cpp index e1fea67..e83800a 100644 --- a/src/NTPClientLib.cpp +++ b/src/ESPNTPClient.cpp @@ -32,6 +32,7 @@ or implied, of German Martin #ifdef ARDUINO_ARCH_ESP8266 #include "NtpClientLib.h" +#include #define DBG_PORT Serial @@ -46,64 +47,52 @@ NTPClient NTP; NTPClient::NTPClient() { - udp = new WiFiUDP (); } bool NTPClient::setNtpServerName(String ntpServerName, int idx) { - char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char)); - if (name == NULL) - return false; - ntpServerName.toCharArray (name, ntpServerName.length () + 1); - DEBUGLOG ("NTP server set to %s\n", name); - free (_ntpServerName); - _ntpServerName = name; - return true; -} - -bool NTPClient::setNtpServerName (char* ntpServerName, int idx) { - char *name = ntpServerName; - if (name == NULL) - return false; - DEBUGLOG ("NTP server set to %s\n", name); - free (_ntpServerName); - _ntpServerName = name; - return true; + char * buffer = (char *)malloc((ntpServerName.length()+1) * sizeof(char)); + if ((idx >= 0) && (idx <= 2)) { + sntp_stop(); + ntpServerName.toCharArray(buffer, ntpServerName.length()+1); + sntp_setservername(idx, buffer); + DEBUGLOG("NTP server %d set to: %s \r\n", idx, buffer); + sntp_init(); + return true; + } + return false; } String NTPClient::getNtpServerName(int idx) { - if ((idx >= 0) && (idx <= 0)) { - return String (_ntpServerName); - } + if ((idx >= 0) && (idx <= 2)) { + return String(sntp_getservername(idx)); + } return ""; } -char* NTPClient::getNtpServerNamePtr (int idx) { - if ((idx >= 0) && (idx <= 0)) { - return _ntpServerName); - } - return ""; -} - bool NTPClient::setTimeZone(int timeZone) { - if ((timeZone >= -11) && (timeZone <= 13)) { + //if ((timeZone >= -11) && (timeZone <= 13)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; setTime(now() + timeDiff * 3600); - setTime (getTime ()); - DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); - return true; - } - return false; + sntp_stop(); + bool result = sntp_set_timezone(timeZone); + sntp_init(); + setTime(getTime()); + DEBUGLOG("NTP time zone set to: %d, result: %s\r\n", timeZone, result?"OK":"error"); + return result; + //return true; + //} + //return false; } int NTPClient::getTimeZone() { - return _timeZone; + return sntp_get_timezone(); } /*void NTPClient::setLastNTPSync(time_t moment) { From 434e40fa779b8286d54992130455af8ee94878e4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 20 Sep 2017 00:21:31 +0200 Subject: [PATCH 04/30] Implement some functions --- examples/NTPClientESP8266/NTPClientLib.cpp | 65 +++++++++++++++------- examples/NTPClientESP8266/NtpClientLib.h | 8 +-- 2 files changed, 49 insertions(+), 24 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 76a4574..3354e04 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -29,8 +29,6 @@ or implied, of German Martin // // -#ifdef ARDUINO_ARCH_ESP8266 - #include "NtpClientLib.h" #define DBG_PORT Serial @@ -42,11 +40,7 @@ or implied, of German Martin #endif -NTPClient NTP; - -NTPClient::NTPClient() -{ - udp = new WiFiUDP (); +NTPClient::NTPClient () { } bool NTPClient::setNtpServerName(String ntpServerName, int idx) @@ -101,8 +95,8 @@ bool NTPClient::setTimeZone(int timeZone) return false; } -boolean sendNTPpacket (IPAddress &address, UDP *udp) { - char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message +boolean sendNTPpacket (const char* address, UDP *udp) { + uint8_t ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message // set all bytes in the buffer to 0 memset (ntpPacketBuffer, 0, NTP_PACKET_SIZE); @@ -149,29 +143,29 @@ time_t NTPClient::getTime () { DEBUGLOGCR(F("-- Transmit NTP Request"));*/ //if (dnsResult == 1) { //If DNS lookup resulted ok - sendNTPpacket (NTP.getNtpServerName ().c_str (), udp); + sendNTPpacket (getNtpServerName ().c_str (), udp); uint32_t beginWait = millis (); while (millis () - beginWait < 1500) { int size = udp->parsePacket (); if (size >= NTP_PACKET_SIZE) { DEBUGLOG ("-- Receive NTP Response\n"); udp->read (ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer - time_t timeValue = NTP.decodeNtpMessage (ntpPacketBuffer); - setSyncInterval (NTP.getLongInterval ()); - NTP.getFirstSync (); // Set firstSync value if not set before + time_t timeValue = decodeNtpMessage (ntpPacketBuffer); + setSyncInterval (getLongInterval ()); + getFirstSync (); // Set firstSync value if not set before DEBUGLOG ("Sync frequency set low\n"); udp->stop (); - NTP.setLastNTPSync (timeValue); - DEBUGLOG ("Succeccful NTP sync at %s", NTP.getTimeDateString (NTP.getLastNTPSync ()).c_str()); + setLastNTPSync (timeValue); + DEBUGLOG ("Succeccful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str()); if (onSyncEvent) onSyncEvent (timeSyncd); return timeValue; } } - DEBUGLOGCR (F ("-- No NTP Response :-(")); - udp.stop (); - setSyncInterval (NTP.getShortInterval ()); // Retry connection more often + DEBUGLOG ("-- No NTP Response :-("); + udp->stop (); + setSyncInterval (getShortInterval ()); // Retry connection more often if (onSyncEvent) onSyncEvent (noResponse); return 0; // return 0 if unable to get the time @@ -190,5 +184,38 @@ time_t NTPClient::s_getTime() { return NTP.getTime(); } +bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, UDP* udp_conn) { + if (!setNtpServerName (ntpServerName)) { + return false; + } + if (!setTimeZone (timeZone)) { + return false; + } + if (udp_conn) + udp = udp_conn; + else + udp = new WiFiUDP (); + + //_timeZone = timeZone; + setDayLight (daylight); + _lastSyncd = 0; + + if (!setInterval (DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { + return false; + } + DEBUGLOG ("Time sync started\r\n"); + + setSyncInterval (getShortInterval ()); + setSyncProvider (s_getTime); + + return true; +} + +bool NTPClient::stop () { + setSyncProvider (NULL); + DEBUGLOG ("Time sync disabled\n"); + + return true; +} -#endif // ARDUINO_ARCH_ESP8266 \ No newline at end of file +NTPClient NTP; \ No newline at end of file diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 047d247..779bf5e 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -72,6 +72,7 @@ using namespace placeholders; #define DEFAULT_NTP_SHORTINTERVAL 5 // Sync interval when sync has not been achieved. 15 seconds #define DEFAULT_NTP_TIMEZONE 0 // Select your local time offset. 0 if UTC time has to be used +const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #ifdef ARDUINO_ARCH_ESP8266 #define NETWORK_TYPE NETWORK_ESP8266 @@ -95,7 +96,6 @@ using namespace placeholders; #include #endif // NETWORK_TYPE -const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #else #error "Incorrect platform. Only ARDUINO and ESP8266 MCUs are valid." @@ -119,9 +119,7 @@ class NTPClient{ /** * Construct NTP client. */ - NTPClient(); - - NTPClient (UDP* udp_conn); + NTPClient (); /** * Starts time synchronization. @@ -130,7 +128,7 @@ class NTPClient{ * @param[in] true if this time zone has dayligth saving. * @param[out] true if everything went ok. */ - bool begin(String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false); + bool begin(String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, UDP* udp_conn = NULL); #ifdef ARDUINO_ARCH_ESP8266 /** From 5adc1a82ed3f24a84364a411e71e2ed36f7569dc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 20 Sep 2017 22:48:57 +0200 Subject: [PATCH 05/30] All functions implemented for ESP8266 --- examples/NTPClientESP8266/NTPClientLib.cpp | 178 +++++++++++++++++++-- examples/NTPClientESP8266/NtpClientLib.h | 49 +++--- 2 files changed, 188 insertions(+), 39 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 3354e04..d83d32d 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -43,7 +43,7 @@ or implied, of German Martin NTPClient::NTPClient () { } -bool NTPClient::setNtpServerName(String ntpServerName, int idx) +bool NTPClient::setNtpServerName(String ntpServerName) { char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char)); if (!name) @@ -55,7 +55,7 @@ bool NTPClient::setNtpServerName(String ntpServerName, int idx) return true; } -bool NTPClient::setNtpServerName (char* ntpServerName, int idx) { +bool NTPClient::setNtpServerName (char* ntpServerName) { char *name = ntpServerName; if (name == NULL) return false; @@ -65,19 +65,13 @@ bool NTPClient::setNtpServerName (char* ntpServerName, int idx) { return true; } -String NTPClient::getNtpServerName(int idx) +String NTPClient::getNtpServerName() { - if ((idx >= 0) && (idx <= 0)) { - return String (_ntpServerName); - } - return ""; + return String (_ntpServerName); } -char* NTPClient::getNtpServerNamePtr (int idx) { - if ((idx >= 0) && (idx <= 0)) { - return _ntpServerName; - } - return ""; +char* NTPClient::getNtpServerNamePtr () { + return _ntpServerName; } bool NTPClient::setTimeZone(int timeZone) @@ -218,4 +212,164 @@ bool NTPClient::stop () { return true; } +bool NTPClient::setInterval (int interval) { + if (interval >= 10) { + if (_longInterval != interval) { + _longInterval = interval; + DEBUGLOG ("Sync interval set to %d\n",interval); + if (timeStatus () != timeSet) + setSyncInterval (interval); + } + return true; + } else + return false; +} + +bool NTPClient::setInterval (int shortInterval, int longInterval) { + if (shortInterval >= 10 && _longInterval >= 10) { + _shortInterval = shortInterval; + _longInterval = longInterval; + if (timeStatus () != timeSet) { + setSyncInterval (shortInterval); + } else { + setSyncInterval (longInterval); + } + DEBUGLOG ("Short sync interval set to %d\n",shortInterval); + DEBUGLOG ("Long sync interval set to %d\n",longInterval); + return true; + } else + return false; +} + +int NTPClient::getInterval () { + return _longInterval; +} + +int NTPClient::getShortInterval () { + return _shortInterval; +} + +void NTPClient::setDayLight (bool daylight) { + _daylight = daylight; + DEBUGLOG ("--Set daylight saving %s\n", daylight ? "ON" : "OFF"); + setTime (getTime ()); +} + +bool NTPClient::getDayLight () { + return _daylight; +} + +String NTPClient::getTimeStr (time_t moment) { + char timeStr[10]; + sprintf (timeStr, "%2d:%2d:%2d", hour (moment), minute (moment), second (moment)); + + return timeStr; +} + +String NTPClient::getDateStr (time_t moment) { + char dateStr[12]; + sprintf (dateStr, "%2d/%2d/%4d", day (moment), month (moment), year (moment)); + + return dateStr; +} + +String NTPClient::getTimeDateString (time_t moment) { + return getTimeStr (moment) + " " + getDateStr (moment); +} + +time_t NTPClient::getLastNTPSync () { + return _lastSyncd; +} + +void NTPClient::onNTPSyncEvent (onSyncEvent_t handler) { + onSyncEvent = handler; +} + +time_t NTPClient::getUptime () { + _uptime = _uptime + (millis () - _uptime); + return _uptime / 1000; +} + +String NTPClient::getUptimeString () { + uint days; + uint8 hours; + uint8 minutes; + uint8 seconds; + + time_t uptime = getUptime (); + + seconds = uptime % SECS_PER_MIN; + uptime -= seconds; + minutes = (uptime % SECS_PER_HOUR) / SECS_PER_MIN; + uptime -= minutes * SECS_PER_MIN; + hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; + uptime -= hours * SECS_PER_HOUR; + days = uptime / SECS_PER_DAY; + + char uptimeStr[20]; + sprintf (uptimeStr, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); + + return uptimeStr; +} + +time_t NTPClient::getLastBootTime () { + if (timeStatus () == timeSet) { + return (now () - getUptime ()); + } + return 0; +} + +time_t NTPClient::getFirstSync () { + if (!_firstSync) { + if (timeStatus () == timeSet) { + _firstSync = now () - getUptime (); + } + } + + return _firstSync; +} + +bool NTPClient::summertime (int year, byte month, byte day, byte hour, byte tzHours) +// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) +{ + if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez + if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep + if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) + return true; + else + return false; +} + +boolean NTPClient::isSummerTimePeriod (time_t moment) { + return summertime (year (), month (), day (), hour (), getTimeZone ()); +} + +void NTPClient::setLastNTPSync (time_t moment) { + _lastSyncd = moment; +} + +time_t NTPClient::decodeNtpMessage (char *messageBuffer) { + unsigned long secsSince1900; + // convert four bytes starting at location 40 to a long integer + secsSince1900 = (unsigned long)messageBuffer[40] << 24; + secsSince1900 |= (unsigned long)messageBuffer[41] << 16; + secsSince1900 |= (unsigned long)messageBuffer[42] << 8; + secsSince1900 |= (unsigned long)messageBuffer[43]; + +#define SEVENTY_YEARS 2208988800UL + time_t timeTemp = secsSince1900 - SEVENTY_YEARS + _timeZone * SECS_PER_HOUR; + + if (_daylight) { + if (summertime (year (timeTemp), month (timeTemp), day (timeTemp), hour (timeTemp), _timeZone)) { + timeTemp += SECS_PER_HOUR; + DEBUGLOG ("Summer Time\n"); + } else { + DEBUGLOG ("Winter Time\n"); + } + } else { + DEBUGLOG ("No daylight\n"); + } + return timeTemp; +} + NTPClient NTP; \ No newline at end of file diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 779bf5e..fc2303d 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -41,10 +41,10 @@ or implied, of German Martin #define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port #ifdef ESP8266 -extern "C" { -#include "user_interface.h" -#include "sntp.h" -} +//extern "C" { +//#include "user_interface.h" +//#include "sntp.h" +//} #include #include #include @@ -130,23 +130,21 @@ class NTPClient{ */ bool begin(String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, UDP* udp_conn = NULL); -#ifdef ARDUINO_ARCH_ESP8266 /** * Sets NTP server name. * @param[in] New NTP server name. - * @param[in] Server index (0-2). * @param[out] True if everything went ok. */ - bool setNtpServerName(String ntpServerName, int idx = 0); - bool setNtpServerName (char* ntpServerName, int idx = 0); + bool setNtpServerName(String ntpServerName); + bool setNtpServerName (char* ntpServerName); /** * Gets NTP server name * @param[in] Server index (0-2). * @param[out] NTP server name. */ - String getNtpServerName(int idx = 0); - char* getNtpServerNamePtr (int idx = 0); + String getNtpServerName(); + char* getNtpServerNamePtr (); /** * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. @@ -154,7 +152,6 @@ class NTPClient{ * @param[out] Time in UNIX time format. */ time_t getTime(); -#endif /** * Sets timezone. @@ -195,7 +192,7 @@ class NTPClient{ * @param[out] Interval for normal operation, in seconds. */ int getInterval(); - + /** * Changes sync period not sync'd status. * @param[out] Interval while time is not first adjusted yet, in seconds. @@ -225,7 +222,7 @@ class NTPClient{ * @param[out] String constructed from current time. * TODO: Add internationalization support */ - String getTimeStr(); + String getTimeStr () { return getTimeStr (now ()); } /** * Convert a time in UNIX format to a String representing time. @@ -240,7 +237,7 @@ class NTPClient{ * @param[out] String constructed from current date. * TODO: Add internationalization support */ - String getDateStr(); + String getDateStr () { return getDateStr (now ()); } /** * Convert a time in UNIX format to a String representing its date. @@ -255,7 +252,7 @@ class NTPClient{ * @param[out] String constructed from current time. * TODO: Add internationalization support */ - String getTimeDateString(); + String getTimeDateString () { return getTimeDateString (now ()); } /** * Convert current time and date to a String. @@ -326,14 +323,15 @@ class NTPClient{ protected: UDP *udp; - bool _daylight; //Does this time zone have daylight saving? - int8_t _timeZone = 0; //Keep track of set time zone offset - int _shortInterval; //Interval to set periodic time sync until first synchronization. - int _longInterval; //Interval to set periodic time sync - time_t _lastSyncd = 0; //Stored time of last successful sync - time_t _firstSync = 0; //Stored time of first successful sync after boot - unsigned long _uptime = 0; // Time since boot - onSyncEvent_t onSyncEvent; // Event handler callback + bool _daylight; ///< Does this time zone have daylight saving? + int8_t _timeZone = 0; ///< Keep track of set time zone offset + char* _ntpServerName; ///< Name of NTP server on Internet or LAN + int _shortInterval; ///< Interval to set periodic time sync until first synchronization. + int _longInterval; ///< Interval to set periodic time sync + time_t _lastSyncd = 0; ///< Stored time of last successful sync + time_t _firstSync = 0; ///< Stored time of first successful sync after boot + unsigned long _uptime = 0; ///< Time since boot + onSyncEvent_t onSyncEvent; ///< Event handler callback /** * Function that gets time from NTP server and convert it to Unix time format @@ -357,11 +355,8 @@ class NTPClient{ * @param[in] Digit to evaluate the need of leading 0. * @param[out] Result digit with leading 0 if needed. */ - String printDigits(int digits); - -//#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 + //String printDigits(int digits); - char* _ntpServerName; public: /** From 7a684215b51e0dd37a26a3c55bdc7ec5cb3533a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 20 Sep 2017 23:20:52 +0200 Subject: [PATCH 06/30] Remove unnecessary libraries --- examples/NTPClientESP8266/NtpClientLib.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index fc2303d..6ab6431 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -88,12 +88,9 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #include #include #elif NETWORK_TYPE == NETWORK_WIFI101 -#include #include #include #include -#include -#include #endif // NETWORK_TYPE From 0c0ffd820b94479d88fdc00494541720692dc387 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 20 Sep 2017 23:36:05 +0200 Subject: [PATCH 07/30] Fix AVR Platform --- examples/NTPClientESP8266/NTPClientLib.cpp | 13 +++++++++---- examples/NTPClientESP8266/NtpClientLib.h | 6 +++--- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index d83d32d..52ddc31 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -188,7 +188,12 @@ bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, UDP* u if (udp_conn) udp = udp_conn; else +#if NETWORK_TYPE == NETWORK_W5100 + udp = new EthernetUDP (); + +#else udp = new WiFiUDP (); +#endif //_timeZone = timeZone; setDayLight (daylight); @@ -291,10 +296,10 @@ time_t NTPClient::getUptime () { } String NTPClient::getUptimeString () { - uint days; - uint8 hours; - uint8 minutes; - uint8 seconds; + uint16_t days; + uint8_t hours; + uint8_t minutes; + uint8_t seconds; time_t uptime = getUptime (); diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 6ab6431..5be2289 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -82,11 +82,11 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message //#define NETWORK_TYPE NETWORK_W5100 #if NETWORK_TYPE == NETWORK_W5100 -#include +//#include #include #include -#include -#include +//#include +//#include #elif NETWORK_TYPE == NETWORK_WIFI101 #include #include From f620b627e365b31bce9996043c794eeeab942d5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Mon, 20 Nov 2017 08:10:11 +0100 Subject: [PATCH 08/30] NTP statechart diagram --- Diagrama de estados.graphml | 299 ++++++++++++++++++++++++++++++++++++ 1 file changed, 299 insertions(+) create mode 100644 Diagrama de estados.graphml diff --git a/Diagrama de estados.graphml b/Diagrama de estados.graphml new file mode 100644 index 0000000..f7d8961 --- /dev/null +++ b/Diagrama de estados.graphml @@ -0,0 +1,299 @@ + + + + + + + + + + + + + + + + + + + + + + + + Inicio + + + + + + + + + + + + + + + + + + Wait_Resp_1 + + + + + + + + + + + + + + + + + + Decode +message + + + + + + + + + + + + + + + + + + Set time + + + + + + + + + + + + + + + + + + + + SendNTPPacket + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Max 1500 ms + + + + + + + + + + + + + + + + + + + + + No Response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Got response + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Decode OK + + + + + + + + + + + + + + + + + + + + + Decode +error + + + + + + + + + + + + + + + + From f2bc568b75d7f9ff96f6f7753d27849d5a2b3dee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 07:35:25 +0100 Subject: [PATCH 09/30] Correct time interval --- examples/NTPClientESP8266/NtpClientLib.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 5be2289..df61d14 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -69,7 +69,7 @@ using namespace placeholders; #define DEFAULT_NTP_SERVER "pool.ntp.org" // Default international NTP server. I recommend you to select a closer server to get better accuracy #define DEFAULT_NTP_PORT 123 // Default local udp port. Select a different one if neccesary (usually not needed) #define DEFAULT_NTP_INTERVAL 1800 // Default sync interval 30 minutes -#define DEFAULT_NTP_SHORTINTERVAL 5 // Sync interval when sync has not been achieved. 15 seconds +#define DEFAULT_NTP_SHORTINTERVAL 15 // Sync interval when sync has not been achieved. 15 seconds #define DEFAULT_NTP_TIMEZONE 0 // Select your local time offset. 0 if UTC time has to be used const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message From 038c6d13d74322f05bc0d341b181240067056f52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 07:36:05 +0100 Subject: [PATCH 10/30] Do not start time sync if udp object is not instantiated --- examples/NTPClientESP8266/NTPClientLib.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 52ddc31..948b26f 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -77,12 +77,13 @@ char* NTPClient::getNtpServerNamePtr () { bool NTPClient::setTimeZone(int timeZone) { if ((timeZone >= -11) && (timeZone <= 13)) { + DEBUGLOG ("Enter here. udp = %d\n", udp); // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; setTime(now() + timeDiff * 3600); - - setTime (getTime ()); + if (udp) + setTime (getTime ()); DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); return true; } From 279b31a3fb20ea3d8976508e44488f8b00d6d3f5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 08:44:25 +0100 Subject: [PATCH 11/30] Add WiFi connection event information --- examples/NTPClientESP8266/NTPClientESP8266.ino | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index c907d30..32b9389 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -47,9 +47,15 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G int8_t timeZone = 1; +void onSTAConnected (WiFiEventStationModeConnected ipInfo) { + Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str()); +} + + // Start NTP only after IP network is connected void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); + Serial.printf ("Connected: %s\r\n", WiFi.status() == WL_CONNECTED? "yes" : "no"); NTP.begin("pool.ntp.org", timeZone, true); NTP.setInterval(63); digitalWrite(ONBOARDLED, LOW); // Turn on LED @@ -82,7 +88,7 @@ NTPSyncEvent_t ntpEvent; // Last triggered event void setup() { - static WiFiEventHandler e1, e2; + static WiFiEventHandler e1, e2, e3; Serial.begin(115200); Serial.println(); @@ -104,7 +110,7 @@ void setup() e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client e2 = WiFi.onStationModeDisconnected(onSTADisconnected); - + e3 = WiFi.onStationModeConnected (onSTAConnected); } void loop() From d538dd1503f6faaeb39dd38c4f5080472a2dd656 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 08:47:15 +0100 Subject: [PATCH 12/30] Correct typos and conditionals --- examples/NTPClientESP8266/NTPClientLib.cpp | 16 ++++++++-------- examples/NTPClientESP8266/NtpClientLib.h | 1 + 2 files changed, 9 insertions(+), 8 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 948b26f..260d0a9 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -108,7 +108,7 @@ boolean sendNTPpacket (const char* address, UDP *udp) { ntpPacketBuffer[15] = 52; // all NTP fields have been given values, now // you can send a packet requesting a timestamp: - udp->beginPacket (address, 123); //NTP requests are to port 123 + udp->beginPacket (address, DEFAULT_NTP_PORT); //NTP requests are to port 123 udp->write(ntpPacketBuffer, NTP_PACKET_SIZE); udp->endPacket (); return true; @@ -140,7 +140,7 @@ time_t NTPClient::getTime () { //if (dnsResult == 1) { //If DNS lookup resulted ok sendNTPpacket (getNtpServerName ().c_str (), udp); uint32_t beginWait = millis (); - while (millis () - beginWait < 1500) { + while (millis () - beginWait < NTP_TIMEOUT) { int size = udp->parsePacket (); if (size >= NTP_PACKET_SIZE) { DEBUGLOG ("-- Receive NTP Response\n"); @@ -151,14 +151,14 @@ time_t NTPClient::getTime () { DEBUGLOG ("Sync frequency set low\n"); udp->stop (); setLastNTPSync (timeValue); - DEBUGLOG ("Succeccful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str()); + DEBUGLOG ("Successful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str()); if (onSyncEvent) onSyncEvent (timeSyncd); return timeValue; } } - DEBUGLOG ("-- No NTP Response :-("); + DEBUGLOG ("-- No NTP Response :-(\n"); udp->stop (); setSyncInterval (getShortInterval ()); // Retry connection more often if (onSyncEvent) @@ -223,7 +223,7 @@ bool NTPClient::setInterval (int interval) { if (_longInterval != interval) { _longInterval = interval; DEBUGLOG ("Sync interval set to %d\n",interval); - if (timeStatus () != timeSet) + if (timeStatus () == timeSet) setSyncInterval (interval); } return true; @@ -232,7 +232,7 @@ bool NTPClient::setInterval (int interval) { } bool NTPClient::setInterval (int shortInterval, int longInterval) { - if (shortInterval >= 10 && _longInterval >= 10) { + if (shortInterval >= 10 && longInterval >= 10) { _shortInterval = shortInterval; _longInterval = longInterval; if (timeStatus () != timeSet) { @@ -267,14 +267,14 @@ bool NTPClient::getDayLight () { String NTPClient::getTimeStr (time_t moment) { char timeStr[10]; - sprintf (timeStr, "%2d:%2d:%2d", hour (moment), minute (moment), second (moment)); + sprintf (timeStr, "%02d:%02d:%02d", hour (moment), minute (moment), second (moment)); return timeStr; } String NTPClient::getDateStr (time_t moment) { char dateStr[12]; - sprintf (dateStr, "%2d/%2d/%4d", day (moment), month (moment), year (moment)); + sprintf (dateStr, "%02d/%02d/%4d", day (moment), month (moment), year (moment)); return dateStr; } diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index df61d14..6ef1d32 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -68,6 +68,7 @@ using namespace placeholders; #define DEFAULT_NTP_SERVER "pool.ntp.org" // Default international NTP server. I recommend you to select a closer server to get better accuracy #define DEFAULT_NTP_PORT 123 // Default local udp port. Select a different one if neccesary (usually not needed) +#define NTP_TIMEOUT 1500 // Response timeout for NTP requests #define DEFAULT_NTP_INTERVAL 1800 // Default sync interval 30 minutes #define DEFAULT_NTP_SHORTINTERVAL 15 // Sync interval when sync has not been achieved. 15 seconds #define DEFAULT_NTP_TIMEZONE 0 // Select your local time offset. 0 if UTC time has to be used From 7878cce401bcdc03475512b4aa95fdb20a72d50b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 08:50:43 +0100 Subject: [PATCH 13/30] Adapt UDP object to selected platform --- examples/NTPClientESP8266/NTPClientLib.cpp | 15 ++++++++++++--- examples/NTPClientESP8266/NtpClientLib.h | 12 ++++++++++-- 2 files changed, 22 insertions(+), 5 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 260d0a9..3f01853 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -123,7 +123,7 @@ time_t NTPClient::getTime () { DEBUGLOG ("Starting UDP"); udp->begin (DEFAULT_NTP_PORT); - DEBUGLOG ("Remote port: %d\n",udp->remotePort()); + DEBUGLOG ("UDP port: %d\n",udp->localPort()); while (udp->parsePacket () > 0); // discard any previously received packets /*dns.begin(WiFi.dnsServerIP()); uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP); @@ -157,6 +157,9 @@ time_t NTPClient::getTime () { onSyncEvent (timeSyncd); return timeValue; } +#ifdef ARDUINO_ARCH_ESP8266 + ESP.wdtFeed (); +#endif } DEBUGLOG ("-- No NTP Response :-(\n"); udp->stop (); @@ -179,11 +182,17 @@ time_t NTPClient::s_getTime() { return NTP.getTime(); } -bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, UDP* udp_conn) { +#if NETWORK_TYPE == NETWORK_W5100 +bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, EthernetUDP* udp_conn) { +#else +bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, WiFiUDP* udp_conn) { +#endif if (!setNtpServerName (ntpServerName)) { + DEBUGLOG ("Time sync not started\r\n"); return false; } if (!setTimeZone (timeZone)) { + DEBUGLOG ("Time sync not started\r\n"); return false; } if (udp_conn) @@ -191,7 +200,6 @@ bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, UDP* u else #if NETWORK_TYPE == NETWORK_W5100 udp = new EthernetUDP (); - #else udp = new WiFiUDP (); #endif @@ -201,6 +209,7 @@ bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, UDP* u _lastSyncd = 0; if (!setInterval (DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { + DEBUGLOG ("Time sync not started\r\n"); return false; } DEBUGLOG ("Time sync started\r\n"); diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 6ef1d32..d80555d 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -126,7 +126,11 @@ class NTPClient{ * @param[in] true if this time zone has dayligth saving. * @param[out] true if everything went ok. */ - bool begin(String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, UDP* udp_conn = NULL); +#if NETWORK_TYPE == NETWORK_W5100 + bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, EthernetUDP* udp_conn = NULL); +#else + bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, WiFiUDP* udp_conn = NULL); +#endif /** * Sets NTP server name. @@ -320,7 +324,11 @@ class NTPClient{ protected: - UDP *udp; +#if NETWORK_TYPE == NETWORK_W5100 + EthernetUDP *udp; +#else + WiFiUDP *udp; +#endif bool _daylight; ///< Does this time zone have daylight saving? int8_t _timeZone = 0; ///< Keep track of set time zone offset char* _ntpServerName; ///< Name of NTP server on Internet or LAN From b17398fb356a7b3e1720acf60e85c453f47f75c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 09:37:13 +0100 Subject: [PATCH 14/30] Sync error at startup --- examples/NTPClientESP8266/NTPClientESP8266.ino | 10 ++++++++-- examples/NTPClientESP8266/NTPClientLib.cpp | 9 +++++---- examples/NTPClientESP8266/NtpClientLib.h | 2 +- 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index 32b9389..6038069 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -46,6 +46,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G #define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 int8_t timeZone = 1; +bool wifiFirstConnected = false; void onSTAConnected (WiFiEventStationModeConnected ipInfo) { Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str()); @@ -56,9 +57,8 @@ void onSTAConnected (WiFiEventStationModeConnected ipInfo) { void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); Serial.printf ("Connected: %s\r\n", WiFi.status() == WL_CONNECTED? "yes" : "no"); - NTP.begin("pool.ntp.org", timeZone, true); - NTP.setInterval(63); digitalWrite(ONBOARDLED, LOW); // Turn on LED + wifiFirstConnected = true; } // Manage network disconnection @@ -118,6 +118,12 @@ void loop() static int i = 0; static int last = 0; + if (wifiFirstConnected) { + wifiFirstConnected = false; + NTP.begin ("pool.ntp.org", timeZone, true, minutesTimeZone); + NTP.setInterval (63); + } + if (syncEventTriggered) { processSyncEvent(ntpEvent); syncEventTriggered = false; diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 3f01853..91831e5 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -74,16 +74,17 @@ char* NTPClient::getNtpServerNamePtr () { return _ntpServerName; } -bool NTPClient::setTimeZone(int timeZone) +bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) { - if ((timeZone >= -11) && (timeZone <= 13)) { - DEBUGLOG ("Enter here. udp = %d\n", udp); + if ((timeZone >= -11) && (timeZone <= 13) && (minutes >= 0) && (minutes <= 59)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; setTime(now() + timeDiff * 3600); if (udp) + if (udp && (timeStatus () != timeNotSet)) { setTime (getTime ()); + } DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); return true; } @@ -121,7 +122,7 @@ time_t NTPClient::getTime () { char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store response message - DEBUGLOG ("Starting UDP"); + DEBUGLOG ("Starting UDP\n"); udp->begin (DEFAULT_NTP_PORT); DEBUGLOG ("UDP port: %d\n",udp->localPort()); while (udp->parsePacket () > 0); // discard any previously received packets diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index d80555d..47925c7 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -160,7 +160,7 @@ class NTPClient{ * @param[in] New time offset in hours (-11 <= timeZone <= +13). * @param[out] True if everything went ok. */ - bool setTimeZone(int timeZone); + bool setTimeZone(int8_t timeZone, int8_t minutes = 0); /** * Gets timezone. From 0e539192990f209c6c63c327d6783cd724d6230d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 09:38:07 +0100 Subject: [PATCH 15/30] Add minutes offset to time zone --- examples/NTPClientESP8266/NTPClientESP8266.ino | 1 + examples/NTPClientESP8266/NTPClientLib.cpp | 14 +++++++------- examples/NTPClientESP8266/NtpClientLib.h | 5 +++-- 3 files changed, 11 insertions(+), 9 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index 6038069..53e627b 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -46,6 +46,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G #define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 int8_t timeZone = 1; +int8_t minutesTimeZone = 0; bool wifiFirstConnected = false; void onSTAConnected (WiFiEventStationModeConnected ipInfo) { diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 91831e5..382986a 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -76,12 +76,12 @@ char* NTPClient::getNtpServerNamePtr () { bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) { - if ((timeZone >= -11) && (timeZone <= 13) && (minutes >= 0) && (minutes <= 59)) { + if ((timeZone >= -11) && (timeZone <= 13) && (minutes >= -59) && (minutes <= 59)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; - setTime(now() + timeDiff * 3600); - if (udp) + _minutesOffset = minutes; + setTime(now() + timeDiff * SECS_PER_HOUR + minutes * SECS_PER_MIN); if (udp && (timeStatus () != timeNotSet)) { setTime (getTime ()); } @@ -184,15 +184,15 @@ time_t NTPClient::s_getTime() { } #if NETWORK_TYPE == NETWORK_W5100 -bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, EthernetUDP* udp_conn) { +bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, EthernetUDP* udp_conn) { #else -bool NTPClient::begin (String ntpServerName, int timeZone, bool daylight, WiFiUDP* udp_conn) { +bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, WiFiUDP* udp_conn) { #endif if (!setNtpServerName (ntpServerName)) { DEBUGLOG ("Time sync not started\r\n"); return false; } - if (!setTimeZone (timeZone)) { + if (!setTimeZone (timeZone, minutes)) { DEBUGLOG ("Time sync not started\r\n"); return false; } @@ -373,7 +373,7 @@ time_t NTPClient::decodeNtpMessage (char *messageBuffer) { secsSince1900 |= (unsigned long)messageBuffer[43]; #define SEVENTY_YEARS 2208988800UL - time_t timeTemp = secsSince1900 - SEVENTY_YEARS + _timeZone * SECS_PER_HOUR; + time_t timeTemp = secsSince1900 - SEVENTY_YEARS + _timeZone * SECS_PER_HOUR + _minutesOffset * SECS_PER_MIN; if (_daylight) { if (summertime (year (timeTemp), month (timeTemp), day (timeTemp), hour (timeTemp), _timeZone)) { diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/examples/NTPClientESP8266/NtpClientLib.h index 47925c7..da9990c 100644 --- a/examples/NTPClientESP8266/NtpClientLib.h +++ b/examples/NTPClientESP8266/NtpClientLib.h @@ -127,9 +127,9 @@ class NTPClient{ * @param[out] true if everything went ok. */ #if NETWORK_TYPE == NETWORK_W5100 - bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, EthernetUDP* udp_conn = NULL); + bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL); #else - bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, WiFiUDP* udp_conn = NULL); + bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL); #endif /** @@ -331,6 +331,7 @@ class NTPClient{ #endif bool _daylight; ///< Does this time zone have daylight saving? int8_t _timeZone = 0; ///< Keep track of set time zone offset + int8_t _minutesOffset = 0; ///< Minutes offset for time zones with decimal numbers char* _ntpServerName; ///< Name of NTP server on Internet or LAN int _shortInterval; ///< Interval to set periodic time sync until first synchronization. int _longInterval; ///< Interval to set periodic time sync From 818e8ec6ae3d045493833728263ddefae512914e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 10:17:56 +0100 Subject: [PATCH 16/30] Fix firstSync calculation --- examples/NTPClientESP8266/NTPClientLib.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/examples/NTPClientESP8266/NTPClientLib.cpp index 382986a..d58430f 100644 --- a/examples/NTPClientESP8266/NTPClientLib.cpp +++ b/examples/NTPClientESP8266/NTPClientLib.cpp @@ -148,7 +148,11 @@ time_t NTPClient::getTime () { udp->read (ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer time_t timeValue = decodeNtpMessage (ntpPacketBuffer); setSyncInterval (getLongInterval ()); - getFirstSync (); // Set firstSync value if not set before + if (!_firstSync) { + // if (timeStatus () == timeSet) + _firstSync = timeValue; + } + //getFirstSync (); // Set firstSync value if not set before DEBUGLOG ("Sync frequency set low\n"); udp->stop (); setLastNTPSync (timeValue); @@ -336,12 +340,11 @@ time_t NTPClient::getLastBootTime () { } time_t NTPClient::getFirstSync () { - if (!_firstSync) { + /*if (!_firstSync) { if (timeStatus () == timeSet) { _firstSync = now () - getUptime (); } - } - + }*/ return _firstSync; } From eb41501f3958da5ef993d4bf01f1ba23c618c2f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 10:21:22 +0100 Subject: [PATCH 17/30] Relocate library files --- .../NTPClientESP8266/NTPClientESP8266.ino | 2 +- src/AvrNTPClient.cpp | 520 ------------------ src/ESPNTPClient.cpp | 386 ------------- .../NTPClientESP8266 => src}/NTPClientLib.cpp | 0 .../NTPClientESP8266 => src}/NtpClientLib.h | 0 5 files changed, 1 insertion(+), 907 deletions(-) delete mode 100644 src/AvrNTPClient.cpp delete mode 100644 src/ESPNTPClient.cpp rename {examples/NTPClientESP8266 => src}/NTPClientLib.cpp (100%) rename {examples/NTPClientESP8266 => src}/NtpClientLib.h (100%) diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index 53e627b..3a8ee37 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -35,7 +35,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G #include #include "WifiConfig.h" -#include "NtpClientLib.h" +#include #include #ifndef WIFI_CONFIG_H diff --git a/src/AvrNTPClient.cpp b/src/AvrNTPClient.cpp deleted file mode 100644 index 9ab227c..0000000 --- a/src/AvrNTPClient.cpp +++ /dev/null @@ -1,520 +0,0 @@ -/* -Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are -permitted provided that the following conditions are met : - -1. Redistributions of source code must retain the above copyright notice, this list of -conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list -of conditions and the following disclaimer in the documentation and / or other materials -provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation are those of the -authors and should not be interpreted as representing official policies, either expressed -or implied, of German Martin -*/ -/* - Name: NtpClientLib.cpp - Created: 21/12/2015 16:26:34 - Author: gmag11@gmail.com - Editor: http://www.visualmicro.com -*/ - -#include "NtpClientLib.h" - -#if defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 - -#define DBG_PORT Serial - -#ifdef DEBUG_NTPCLIENT -#define DEBUGLOG(A) DBG_PORT.print(A) -#define DEBUGLOGCR(A) DBG_PORT.println(A) -#else -#define DEBUGLOG(A) -#define DEBUGLOGCR(A) -#endif - - -NTPClient NTP; - -#if NETWORK_TYPE == NETWORK_W5100 -// send an NTP request to the time server at the given address -boolean sendNTPpacket(IPAddress &address, EthernetUDP udp) { - char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message - - // set all bytes in the buffer to 0 - memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode - ntpPacketBuffer[1] = 0; // Stratum, or type of clock - ntpPacketBuffer[2] = 6; // Polling Interval - ntpPacketBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - ntpPacketBuffer[12] = 49; - ntpPacketBuffer[13] = 0x4E; - ntpPacketBuffer[14] = 49; - ntpPacketBuffer[15] = 52; - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - udp.beginPacket(address, 123); //NTP requests are to port 123 - udp.write(ntpPacketBuffer, NTP_PACKET_SIZE); - udp.endPacket(); - return true; -} - -/** -* Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. -* @param[out] Time in UNIX time format. Seconds since 1st january 1970. -*/ -time_t getTime() { - DNSClient dns; - EthernetUDP udp; - IPAddress timeServerIP; //NTP server IP address - char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store response message - - - DEBUGLOGCR(F("Starting UDP")); - udp.begin(DEFAULT_NTP_PORT); - DEBUGLOG(F("Remote port: ")); - DEBUGLOGCR(udp.remotePort()); - while (udp.parsePacket() > 0); // discard any previously received packets - dns.begin(Ethernet.dnsServerIP()); - uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP); - DEBUGLOG(F("NTP Server hostname: ")); - DEBUGLOGCR(NTP.getNtpServerName()); - DEBUGLOG(F("NTP Server IP address: ")); - DEBUGLOGCR(timeServerIP); - DEBUGLOG(F("Result code: ")); - DEBUGLOG(dnsResult); - DEBUGLOG(" "); - DEBUGLOGCR(F("-- IP Connected. Waiting for sync")); - DEBUGLOGCR(F("-- Transmit NTP Request")); - - if (dnsResult == 1) { //If DNS lookup resulted ok - sendNTPpacket(timeServerIP,udp); - uint32_t beginWait = millis(); - while (millis() - beginWait < 1500) { - int size = udp.parsePacket(); - if (size >= NTP_PACKET_SIZE) { - DEBUGLOGCR(F("-- Receive NTP Response")); - udp.read(ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer - time_t timeValue = NTP.decodeNtpMessage(ntpPacketBuffer); - setSyncInterval(NTP.getLongInterval()); - NTP.getFirstSync(); // Set firstSync value if not set before - DEBUGLOGCR(F("Sync frequency set low")); - udp.stop(); - NTP.setLastNTPSync(timeValue); - DEBUGLOG(F("Succeccful NTP sync at ")); - DEBUGLOGCR(NTP.getTimeDateString(NTP.getLastNTPSync())); - - if (onSyncEvent) - onSyncEvent(timeSyncd); - return timeValue; - } - } - DEBUGLOGCR(F("-- No NTP Response :-(")); - udp.stop(); - setSyncInterval(NTP.getShortInterval()); // Retry connection more often - if (onSyncEvent) - onSyncEvent(noResponse); - return 0; // return 0 if unable to get the time - } - else { - DEBUGLOGCR(F("-- Invalid address :-((")); - if (onSyncEvent) - onSyncEvent(invalidAddress); - udp.stop(); - return 0; // return 0 if unable to get the time - } -} -#elif NETWORK_TYPE == NETWORK_WIFI101 -// send an NTP request to the time server at the given address -boolean sendNTPpacket(const char* address, WiFiUDP udp) { - char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store request message - - // set all bytes in the buffer to 0 - memset(ntpPacketBuffer, 0, NTP_PACKET_SIZE); - // Initialize values needed to form NTP request - // (see URL above for details on the packets) - ntpPacketBuffer[0] = 0b11100011; // LI, Version, Mode - ntpPacketBuffer[1] = 0; // Stratum, or type of clock - ntpPacketBuffer[2] = 6; // Polling Interval - ntpPacketBuffer[3] = 0xEC; // Peer Clock Precision - // 8 bytes of zero for Root Delay & Root Dispersion - ntpPacketBuffer[12] = 49; - ntpPacketBuffer[13] = 0x4E; - ntpPacketBuffer[14] = 49; - ntpPacketBuffer[15] = 52; - // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: - udp.beginPacket(address, 123); //NTP requests are to port 123 - udp.write(ntpPacketBuffer, NTP_PACKET_SIZE); - udp.endPacket(); - return true; -} - -/** -* Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. -* @param[out] Time in UNIX time format. Seconds since 1st january 1970. -*/ -time_t getTime() { - DNSClient dns; - WiFiUDP udp; - IPAddress timeServerIP; //NTP server IP address - char ntpPacketBuffer[NTP_PACKET_SIZE]; //Buffer to store response message - - - DEBUGLOGCR(F("Starting UDP")); - udp.begin(DEFAULT_NTP_PORT); - DEBUGLOG(F("Remote port: ")); - DEBUGLOGCR(udp.remotePort()); - while (udp.parsePacket() > 0); // discard any previously received packets - /*dns.begin(WiFi.dnsServerIP()); - uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP); - DEBUGLOG(F("NTP Server hostname: ")); - DEBUGLOGCR(NTP.getNtpServerName()); - DEBUGLOG(F("NTP Server IP address: ")); - DEBUGLOGCR(timeServerIP); - DEBUGLOG(F("Result code: ")); - DEBUGLOG(dnsResult); - DEBUGLOG(" "); - DEBUGLOGCR(F("-- IP Connected. Waiting for sync")); - DEBUGLOGCR(F("-- Transmit NTP Request"));*/ - - //if (dnsResult == 1) { //If DNS lookup resulted ok - sendNTPpacket(NTP.getNtpServerName().c_str(), udp); - uint32_t beginWait = millis(); - while (millis() - beginWait < 1500) { - int size = udp.parsePacket(); - if (size >= NTP_PACKET_SIZE) { - DEBUGLOGCR(F("-- Receive NTP Response")); - udp.read(ntpPacketBuffer, NTP_PACKET_SIZE); // read packet into the buffer - time_t timeValue = NTP.decodeNtpMessage(ntpPacketBuffer); - setSyncInterval(NTP.getLongInterval()); - NTP.getFirstSync(); // Set firstSync value if not set before - DEBUGLOGCR(F("Sync frequency set low")); - udp.stop(); - NTP.setLastNTPSync(timeValue); - DEBUGLOG(F("Succeccful NTP sync at ")); - DEBUGLOGCR(NTP.getTimeDateString(NTP.getLastNTPSync())); - - if (onSyncEvent) - onSyncEvent(timeSyncd); - return timeValue; - } - } - DEBUGLOGCR(F("-- No NTP Response :-(")); - udp.stop(); - setSyncInterval(NTP.getShortInterval()); // Retry connection more often - if (onSyncEvent) - onSyncEvent(noResponse); - return 0; // return 0 if unable to get the time -} - -#endif //NETWORK_TYPE - -NTPClient::NTPClient() { -} - -bool NTPClient::begin(String ntpServerName, int timeOffset, bool daylight) { - if (!setNtpServerName(ntpServerName)) { - return false; - } - if (!setTimeZone(timeOffset)) { - return false; - } - //sntp_init(); - setDayLight(daylight); - - if (!setInterval(DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { - return false; -} - DEBUGLOGCR(F("Time sync started")); - - setSyncInterval(getShortInterval()); - setSyncProvider(getTime); - - return true; -} - -boolean NTPClient::stop() { - setSyncProvider(NULL); - DEBUGLOGCR(F("Time sync disabled")); - - return true; -} - -time_t NTPClient::decodeNtpMessage(char *messageBuffer) { - unsigned long secsSince1900; - // convert four bytes starting at location 40 to a long integer - secsSince1900 = (unsigned long)messageBuffer[40] << 24; - secsSince1900 |= (unsigned long)messageBuffer[41] << 16; - secsSince1900 |= (unsigned long)messageBuffer[42] << 8; - secsSince1900 |= (unsigned long)messageBuffer[43]; - -#define SEVENTY_YEARS 2208988800UL - time_t timeTemp = secsSince1900 - SEVENTY_YEARS + _timeZone * SECS_PER_HOUR; - - if (_daylight) { - if (summertime(year(timeTemp), month(timeTemp), day(timeTemp), hour(timeTemp), _timeZone)) { - timeTemp += SECS_PER_HOUR; - DEBUGLOGCR(F("Summer Time")); - } - else { - DEBUGLOGCR(F("Winter Time")); - } - } - else { - DEBUGLOGCR(F("No daylight")); - } - return timeTemp; -} - -String NTPClient::getTimeStr(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += printDigits(hour(moment)); - timeStr += ":"; - timeStr += printDigits(minute(moment)); - timeStr += ":"; - timeStr += printDigits(second(moment)); - - return timeStr; - } - else return F("Time not set"); -} - -String NTPClient::getTimeStr() { - return getTimeStr(now()); -} - -String NTPClient::getDateStr(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - - timeStr += printDigits(day(moment)); - timeStr += "/"; - timeStr += printDigits(month(moment)); - timeStr += "/"; - timeStr += String(year(moment)); - - return timeStr; - } - else return F("Date not set"); -} - -String NTPClient::getDateStr() { - return getDateStr(now()); -} - -String NTPClient::getTimeDateString(time_t moment) { - if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += getTimeStr(moment); - timeStr += " "; - timeStr += getDateStr(moment); - - return timeStr; - } else { - return F("Time not set"); - } -} - -String NTPClient::getTimeDateString() { - return getTimeDateString(now()); -} - -String NTPClient::printDigits(int digits) { - // utility for digital clock display: prints preceding colon and leading 0 - String digStr = ""; - - if (digits < 10) - digStr += '0'; - digStr += String(digits); - - return digStr; -} - -int NTPClient::getInterval() -{ - return _longInterval; -} - -int NTPClient::getShortInterval() -{ - return _shortInterval; -} - -boolean NTPClient::getDayLight() -{ - return this->_daylight; -} - -int NTPClient::getTimeZone() -{ - return _timeZone; -} - -String NTPClient::getNtpServerName() -{ - return String(_ntpServerName); -} - -boolean NTPClient::setNtpServerName(String ntpServerName) { - char * name = (char *)malloc((ntpServerName.length() + 1) * sizeof(char)); - ntpServerName.toCharArray(name, ntpServerName.length() + 1); - DEBUGLOG(F("NTP server set to ")); - DEBUGLOGCR(name); - free(_ntpServerName); - _ntpServerName = name; - return true; -} - -boolean NTPClient::setInterval(int interval) -{ - if (interval >= 10) { - if (_longInterval != interval) { - _longInterval = interval; - DEBUGLOG(F("Sync interval set to ")); - DEBUGLOGCR(interval); - if(timeStatus() != timeSet) - setSyncInterval(interval); - } - return true; - } - else - return false; -} - -boolean NTPClient::setInterval(int shortInterval, int longInterval) { - if (shortInterval >= 10 && _longInterval >= 10) { - _shortInterval = shortInterval; - _longInterval = longInterval; - if (timeStatus() != timeSet) { - setSyncInterval(shortInterval); - } - else { - setSyncInterval(longInterval); - } - DEBUGLOG(F("Short sync interval set to ")); DEBUGLOGCR(shortInterval); - DEBUGLOG(F("Long sync interval set to ")); DEBUGLOGCR(longInterval); - return true; - } - else - return false; -} - - -boolean NTPClient::setTimeZone(int timeZone) -{ - if (timeZone >= -11 || timeZone <= 13) { - _timeZone = timeZone; - DEBUGLOGCR(F("Time zone set to ")); - DEBUGLOGCR(_timeZone); - setTime(getTime()); - return true; - } - else - return false; -} - -void NTPClient::setDayLight(boolean daylight) -{ - _daylight = daylight; - DEBUGLOG(F("--Set daylight saving to ")); - DEBUGLOGCR(daylight); - setTime(getTime()); -} - -// -// Summertime calculates the daylight saving for a given date. -// -boolean NTPClient::summertime(int year, byte month, byte day, byte hour, byte tzHours) -// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) -{ - if (month<3 || month>10) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez - if (month>3 && month<10) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep - if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) - return true; - else - return false; -} - -time_t NTPClient::getLastNTPSync() { - return _lastSyncd; -} - -void NTPClient::setLastNTPSync(time_t moment) { - _lastSyncd = moment; -} - -time_t NTPClient::getLastBootTime() { - if (timeStatus() == timeSet) { - return (now() - getUptime()); - } - return 0; -} - -time_t NTPClient::getUptime() -{ - _uptime = _uptime + (millis() - _uptime); // Add time since last getUptime call - return _uptime / 1000; -} - -String NTPClient::getUptimeString() { - unsigned int days; - unsigned char hours; - unsigned char minutes; - unsigned char seconds; - - long uptime = getUptime(); - - seconds = uptime % SECS_PER_MIN; - uptime -= seconds; - minutes = (uptime % SECS_PER_HOUR) / SECS_PER_MIN; - uptime -= minutes * SECS_PER_MIN; - hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; - uptime -= hours * SECS_PER_HOUR; - days = uptime / SECS_PER_DAY; - - String uptimeStr = ""; - char buffer[20]; - sprintf(buffer, "%4d days %02d:%02d:%02d", days, hours, minutes, seconds); - uptimeStr += buffer; - - return uptimeStr; -} - -time_t NTPClient::getFirstSync() -{ - if (!_firstSync) { - if (timeStatus() == timeSet) { - _firstSync = now() - getUptime(); - } - } - - return _firstSync; -} - -void NTPClient::onNTPSyncEvent(onSyncEvent_t handler) { - onSyncEvent = handler; -} - -boolean NTPClient::isSummerTimePeriod(time_t moment) { - return summertime(year(), month(), day(), hour(), getTimeZone()); -} - -#endif // ARDUINO_ARCH_AVR \ No newline at end of file diff --git a/src/ESPNTPClient.cpp b/src/ESPNTPClient.cpp deleted file mode 100644 index e83800a..0000000 --- a/src/ESPNTPClient.cpp +++ /dev/null @@ -1,386 +0,0 @@ -/* -Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. - -Redistribution and use in source and binary forms, with or without modification, are -permitted provided that the following conditions are met : - -1. Redistributions of source code must retain the above copyright notice, this list of -conditions and the following disclaimer. - -2. Redistributions in binary form must reproduce the above copyright notice, this list -of conditions and the following disclaimer in the documentation and / or other materials -provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED -WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR -CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON -ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING -NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - -The views and conclusions contained in the software and documentation are those of the -authors and should not be interpreted as representing official policies, either expressed -or implied, of German Martin -*/ -// -// -// - -#ifdef ARDUINO_ARCH_ESP8266 - -#include "NtpClientLib.h" -#include - -#define DBG_PORT Serial - -#ifdef DEBUG_NTPCLIENT -#define DEBUGLOG(...) DBG_PORT.printf(__VA_ARGS__) -#else -#define DEBUGLOG(...) -#endif - - -NTPClient NTP; - -NTPClient::NTPClient() -{ -} - -bool NTPClient::setNtpServerName(String ntpServerName, int idx) -{ - char * buffer = (char *)malloc((ntpServerName.length()+1) * sizeof(char)); - if ((idx >= 0) && (idx <= 2)) { - sntp_stop(); - ntpServerName.toCharArray(buffer, ntpServerName.length()+1); - sntp_setservername(idx, buffer); - DEBUGLOG("NTP server %d set to: %s \r\n", idx, buffer); - sntp_init(); - return true; - } - return false; -} - -String NTPClient::getNtpServerName(int idx) -{ - if ((idx >= 0) && (idx <= 2)) { - return String(sntp_getservername(idx)); - } - return ""; -} - -bool NTPClient::setTimeZone(int timeZone) -{ - //if ((timeZone >= -11) && (timeZone <= 13)) { - // Temporarily set time to new time zone, before trying to synchronize - int8_t timeDiff = timeZone - _timeZone; - _timeZone = timeZone; - setTime(now() + timeDiff * 3600); - - sntp_stop(); - bool result = sntp_set_timezone(timeZone); - sntp_init(); - setTime(getTime()); - DEBUGLOG("NTP time zone set to: %d, result: %s\r\n", timeZone, result?"OK":"error"); - return result; - //return true; - //} - //return false; -} - -int NTPClient::getTimeZone() -{ - return sntp_get_timezone(); -} - -/*void NTPClient::setLastNTPSync(time_t moment) { - _lastSyncd = moment; -}*/ - -time_t NTPClient::s_getTime() { - return NTP.getTime(); -} - -time_t NTPClient::getTime() -{ - DEBUGLOG("-- NTP Server hostname: %s\r\n", sntp_getservername(0)); - if (WiFi.isConnected()) { - DEBUGLOG("-- Transmit NTP Request\r\n"); - uint32 secsSince1970 = sntp_get_current_timestamp(); - NTP.getUptime(); // Keep uptime updated to avoid overflow if not called - if (secsSince1970) { - setSyncInterval(NTP.getInterval()); // Normal refresh frequency - DEBUGLOG("Sync frequency set low\r\n"); - if (_daylight) { - if (summertime(year(secsSince1970), month(secsSince1970), day(secsSince1970), hour(secsSince1970), getTimeZone())) { - secsSince1970 += SECS_PER_HOUR; - DEBUGLOG("Summer Time\r\n"); - } - else { - DEBUGLOG("Winter Time\r\n"); - } - - } - else { - DEBUGLOG("No daylight\r\n"); - - } - getFirstSync(); - _lastSyncd = secsSince1970; - if (!_firstSync) { // first sync is not set - _firstSync = secsSince1970; - DEBUGLOG("First sync! %s\r\n", getTimeDateString(getFirstSync()).c_str()); - } - DEBUGLOG("Succeccful NTP sync at %s\r\n", getTimeDateString(getLastNTPSync()).c_str()); - } - else { - DEBUGLOG("-- NTP error :-(\r\n"); - setSyncInterval(getShortInterval()); // Fast refresh frequency, until successful sync - if (onSyncEvent) - onSyncEvent(noResponse); - if (!_firstSync) // first sync is not set - return 0; - else - return now(); - } - - if (onSyncEvent) - onSyncEvent(timeSyncd); - return secsSince1970; - } - else { - DEBUGLOG("-- NTP Error. WiFi not connected.\r\n"); - if (onSyncEvent) - onSyncEvent(noResponse); - if (!_firstSync) // first sync is not set - return 0; - else - return now(); - } -} - -bool NTPClient::begin(String ntpServerName, int timeZone, bool daylight) -{ - if (!setNtpServerName(ntpServerName)) { - return false; - } - if (!setTimeZone(timeZone)) { - return false; - } - _timeZone = timeZone; - sntp_init(); - setDayLight(daylight); - _lastSyncd = 0; - - if (!setInterval(DEFAULT_NTP_SHORTINTERVAL, DEFAULT_NTP_INTERVAL)) { - return false; - } - DEBUGLOG("Time sync started\r\n"); - - setSyncInterval(getShortInterval()); - setSyncProvider(s_getTime); - - return true; -} - -bool NTPClient::stop() { - setSyncProvider(NULL); - DEBUGLOG("Time sync disabled\r\n"); - sntp_stop(); - return true; -} - -bool NTPClient::setInterval(int interval) -{ - if (interval >= 10) { - if (_longInterval != interval) { - _longInterval = interval; - DEBUGLOG("Long sync interval set to %d\r\n", interval); - if (timeStatus() == timeSet) - setSyncInterval(interval); - } - return true; - } - DEBUGLOG("Error setting interval %d\r\n", interval); - - return false; -} - -bool NTPClient::setInterval(int shortInterval, int longInterval) { - if (shortInterval >= 5 && longInterval >= 10) { - _shortInterval = shortInterval; - _longInterval = longInterval; - if (timeStatus() != timeSet) { - setSyncInterval(shortInterval); - } - else { - setSyncInterval(longInterval); - } - DEBUGLOG("Short sync interval set to %d\r\n", shortInterval); - DEBUGLOG("Long sync interval set to %d\r\n", longInterval); - return true; - } - DEBUGLOG("Error setting interval. Short: %d Long: %d\r\n", shortInterval, longInterval); - return false; -} - -int NTPClient::getInterval() -{ - return _longInterval; -} - -int NTPClient::getShortInterval() -{ - return _shortInterval; -} - -void NTPClient::setDayLight(bool daylight) -{ - _daylight = daylight; - DEBUGLOG("--Set daylight %s\r\n", daylight? "ON" : "OFF"); - setTime(getTime()); -} - -bool NTPClient::getDayLight() -{ - return _daylight; -} - -String NTPClient::getTimeStr(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += printDigits(hour(moment)); - timeStr += ":"; - timeStr += printDigits(minute(moment)); - timeStr += ":"; - timeStr += printDigits(second(moment)); - - return timeStr; - //} - //else return "Time not set"; -} - -String NTPClient::getTimeStr() { - return getTimeStr(now()); -} - -String NTPClient::getDateStr(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - - timeStr += printDigits(day(moment)); - timeStr += "/"; - timeStr += printDigits(month(moment)); - timeStr += "/"; - timeStr += String(year(moment)); - - return timeStr; - //} - //else return "Date not set"; -} - -String NTPClient::getDateStr() { - return getDateStr(now()); -} - -String NTPClient::getTimeDateString(time_t moment) { - //if ((timeStatus() != timeNotSet) || (moment != 0)) { - String timeStr = ""; - timeStr += getTimeStr(moment); - timeStr += " "; - timeStr += getDateStr(moment); - - return timeStr; - //} - //else return "Time not set"; -} - -String NTPClient::getTimeDateString() { - return getTimeDateString(now()); -} - -String NTPClient::printDigits(int digits) { - // utility for digital clock display: prints preceding colon and leading 0 - String digStr = ""; - - if (digits < 10) - digStr += '0'; - digStr += String(digits); - - return digStr; -} - -bool NTPClient::summertime(int year, byte month, byte day, byte hour, byte tzHours) -// input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) -{ - if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez - if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep - if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) - return true; - else - return false; -} - -time_t NTPClient::getLastBootTime() { - if (timeStatus() == timeSet) { - return (now() - getUptime()); - } - return 0; -} - -time_t NTPClient::getUptime() -{ - _uptime = _uptime + (millis() - _uptime); - return _uptime / 1000; -} - -time_t NTPClient::getFirstSync() -{ - if (!_firstSync) { - if (timeStatus() == timeSet) { - _firstSync = now() - getUptime(); - } - } - - return _firstSync; -} - -String NTPClient::getUptimeString() { - uint days; - uint8 hours; - uint8 minutes; - uint8 seconds; - - long uptime = getUptime(); - - seconds = uptime % SECS_PER_MIN; - uptime -= seconds; - minutes = (uptime % SECS_PER_HOUR)/ SECS_PER_MIN; - uptime -= minutes * SECS_PER_MIN; - hours = (uptime % SECS_PER_DAY) / SECS_PER_HOUR; - uptime -= hours * SECS_PER_HOUR; - days = uptime / SECS_PER_DAY; - - String uptimeStr = ""; - char buffer[20]; - sprintf(buffer, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); - uptimeStr += buffer; - - return uptimeStr; -} - -time_t NTPClient::getLastNTPSync() { - return _lastSyncd; -} - -void NTPClient::onNTPSyncEvent(onSyncEvent_t handler) { - onSyncEvent = handler; -} - -boolean NTPClient::isSummerTimePeriod(time_t moment) { - return summertime(year(), month(), day(), hour(), getTimeZone()); -} - -#endif // ARDUINO_ARCH_ESP8266 \ No newline at end of file diff --git a/examples/NTPClientESP8266/NTPClientLib.cpp b/src/NTPClientLib.cpp similarity index 100% rename from examples/NTPClientESP8266/NTPClientLib.cpp rename to src/NTPClientLib.cpp diff --git a/examples/NTPClientESP8266/NtpClientLib.h b/src/NtpClientLib.h similarity index 100% rename from examples/NTPClientESP8266/NtpClientLib.h rename to src/NtpClientLib.h From e9834371675b412bb679805ce79475f8431ad312 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 11:00:44 +0100 Subject: [PATCH 18/30] Fix AVR platform --- src/NTPClientLib.cpp | 4 ++-- src/NtpClientLib.h | 12 ++++++------ 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index d58430f..8015066 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -124,7 +124,7 @@ time_t NTPClient::getTime () { DEBUGLOG ("Starting UDP\n"); udp->begin (DEFAULT_NTP_PORT); - DEBUGLOG ("UDP port: %d\n",udp->localPort()); + //DEBUGLOG ("UDP port: %d\n",udp->localPort()); while (udp->parsePacket () > 0); // discard any previously received packets /*dns.begin(WiFi.dnsServerIP()); uint8_t dnsResult = dns.getHostByName(NTP.getNtpServerName().c_str(), timeServerIP); @@ -189,7 +189,7 @@ time_t NTPClient::s_getTime() { #if NETWORK_TYPE == NETWORK_W5100 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, EthernetUDP* udp_conn) { -#else +#elif NETWORK_TYPE == NETWORK_ESP8266 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, WiFiUDP* udp_conn) { #endif if (!setNtpServerName (ntpServerName)) { diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index da9990c..bb0db2d 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -38,7 +38,7 @@ or implied, of German Martin #ifndef _NtpClientLib_h #define _NtpClientLib_h -#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port +//#define DEBUG_NTPCLIENT //Uncomment this to enable debug messages over serial port #ifdef ESP8266 //extern "C" { @@ -77,10 +77,10 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #ifdef ARDUINO_ARCH_ESP8266 #define NETWORK_TYPE NETWORK_ESP8266 - -#elif defined ARDUINO_ARCH_AVR || defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 +#elif defined ARDUINO_ARCH_SAMD || defined ARDUINO_ARCH_ARC32 #define NETWORK_TYPE NETWORK_WIFI101 // SET YOUR NETWORK INTERFACE -//#define NETWORK_TYPE NETWORK_W5100 +#elif defined ARDUINO_ARCH_AVR +#define NETWORK_TYPE NETWORK_W5100 #if NETWORK_TYPE == NETWORK_W5100 //#include @@ -128,7 +128,7 @@ class NTPClient{ */ #if NETWORK_TYPE == NETWORK_W5100 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL); -#else +#elif NETWORK_TYPE == NETWORK_ESP8266 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL); #endif @@ -326,7 +326,7 @@ class NTPClient{ #if NETWORK_TYPE == NETWORK_W5100 EthernetUDP *udp; -#else +#elif NETWORK_TYPE == NETWORK_ESP8266 WiFiUDP *udp; #endif bool _daylight; ///< Does this time zone have daylight saving? From 88fab729fd8c6240b5f24c204ab37b9730a1484c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 11:32:27 +0100 Subject: [PATCH 19/30] getTimeZoneMinutes --- src/NTPClientLib.cpp | 6 +++++- src/NtpClientLib.h | 3 ++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index 8015066..45feb35 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -174,11 +174,15 @@ time_t NTPClient::getTime () { return 0; // return 0 if unable to get the time } -int NTPClient::getTimeZone() +int8_t NTPClient::getTimeZone() { return _timeZone; } +int8_t NTPClient::getTimeZoneMinutes () { + return _minutesOffset; +} + /*void NTPClient::setLastNTPSync(time_t moment) { _lastSyncd = moment; }*/ diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index bb0db2d..06697de 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -166,7 +166,8 @@ class NTPClient{ * Gets timezone. * @param[out] Time offset in hours (plus or minus). */ - int getTimeZone(); + int8_t getTimeZone(); + int8_t getTimeZoneMinutes (); /** * Stops time synchronization. From dbe30bb009b7994cf91ea542b5d711109cefecd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 27 Dec 2017 23:55:44 +0100 Subject: [PATCH 20/30] Correct comments --- src/NtpClientLib.h | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index 06697de..d9b3b19 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -124,6 +124,8 @@ class NTPClient{ * @param[in] NTP server name as String. * @param[in] Time offset from UTC. * @param[in] true if this time zone has dayligth saving. + * @param[in] Minutes offset added to hourly offset (optional). + * @param[in] UDP connection instance (optional). * @param[out] true if everything went ok. */ #if NETWORK_TYPE == NETWORK_W5100 @@ -167,6 +169,11 @@ class NTPClient{ * @param[out] Time offset in hours (plus or minus). */ int8_t getTimeZone(); + + /** + * Gets minutes fraction of timezone. + * @param[out] Minutes offset (plus or minus) added to hourly offset. + */ int8_t getTimeZoneMinutes (); /** From a7d9f86e6be320f7d2b080f490012efad38e2f2a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Thu, 28 Dec 2017 00:08:14 +0100 Subject: [PATCH 21/30] Fix SAMD architecture --- src/NTPClientLib.cpp | 2 +- src/NtpClientLib.h | 16 ++++++++-------- 2 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index 45feb35..f86c5be 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -193,7 +193,7 @@ time_t NTPClient::s_getTime() { #if NETWORK_TYPE == NETWORK_W5100 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, EthernetUDP* udp_conn) { -#elif NETWORK_TYPE == NETWORK_ESP8266 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, WiFiUDP* udp_conn) { #endif if (!setNtpServerName (ntpServerName)) { diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index d9b3b19..ee11fcc 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -46,9 +46,6 @@ or implied, of German Martin //#include "sntp.h" //} #include -#include -#include -#include using namespace std; using namespace placeholders; #endif @@ -81,6 +78,7 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #define NETWORK_TYPE NETWORK_WIFI101 // SET YOUR NETWORK INTERFACE #elif defined ARDUINO_ARCH_AVR #define NETWORK_TYPE NETWORK_W5100 +#endif #if NETWORK_TYPE == NETWORK_W5100 //#include @@ -92,12 +90,14 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #include #include #include -#endif // NETWORK_TYPE - +#elif NETWORK_TYPE == NETWORK_ESP8266 +#include +#include +#include #else #error "Incorrect platform. Only ARDUINO and ESP8266 MCUs are valid." -#endif +#endif // NETWORK_TYPE typedef enum { timeSyncd, // Time successfully got from NTP server @@ -130,7 +130,7 @@ class NTPClient{ */ #if NETWORK_TYPE == NETWORK_W5100 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL); -#elif NETWORK_TYPE == NETWORK_ESP8266 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL); #endif @@ -334,7 +334,7 @@ class NTPClient{ #if NETWORK_TYPE == NETWORK_W5100 EthernetUDP *udp; -#elif NETWORK_TYPE == NETWORK_ESP8266 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 WiFiUDP *udp; #endif bool _daylight; ///< Does this time zone have daylight saving? From e4abeb1e2e4634005831bc2d3d7c68ae36029b4e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Thu, 28 Dec 2017 00:19:58 +0100 Subject: [PATCH 22/30] Start ESP32 support --- src/NTPClientLib.cpp | 2 +- src/NtpClientLib.h | 14 ++++++++++---- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index f86c5be..5439d80 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -193,7 +193,7 @@ time_t NTPClient::s_getTime() { #if NETWORK_TYPE == NETWORK_W5100 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, EthernetUDP* udp_conn) { -#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32 bool NTPClient::begin (String ntpServerName, int8_t timeZone, bool daylight, int8_t minutes, WiFiUDP* udp_conn) { #endif if (!setNtpServerName (ntpServerName)) { diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index ee11fcc..7933648 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -62,6 +62,7 @@ using namespace placeholders; #define NETWORK_ENC28J60 (2) // Alternate Ethernet Shield #define NETWORK_WIFI101 (3) // WiFi Shield 101 or MKR1000 #define NETWORK_ESP8266 (100) // ESP8266 boards, not for Arduino using AT firmware +#define NETWORK_ESP32 (101) // ESP32 boards #define DEFAULT_NTP_SERVER "pool.ntp.org" // Default international NTP server. I recommend you to select a closer server to get better accuracy #define DEFAULT_NTP_PORT 123 // Default local udp port. Select a different one if neccesary (usually not needed) @@ -78,6 +79,8 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #define NETWORK_TYPE NETWORK_WIFI101 // SET YOUR NETWORK INTERFACE #elif defined ARDUINO_ARCH_AVR #define NETWORK_TYPE NETWORK_W5100 +#elif defined ARDUINO_ARCH_ESP32 +#define NETWORK_TYPE NETWORK_ESP32 #endif #if NETWORK_TYPE == NETWORK_W5100 @@ -94,7 +97,10 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #include #include #include - +#elif NETWORK_TYPE == NETWORK_ESP32 +#include +#include +#include #else #error "Incorrect platform. Only ARDUINO and ESP8266 MCUs are valid." #endif // NETWORK_TYPE @@ -105,7 +111,7 @@ typedef enum { invalidAddress // Address not reachable } NTPSyncEvent_t; -#ifdef ARDUINO_ARCH_ESP8266 +#if defined ARDUINO_ARCH_ESP8266 || defined ARDUINO_ARCH_ESP32 #include typedef std::function onSyncEvent_t; #else @@ -130,7 +136,7 @@ class NTPClient{ */ #if NETWORK_TYPE == NETWORK_W5100 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL); -#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL); #endif @@ -334,7 +340,7 @@ class NTPClient{ #if NETWORK_TYPE == NETWORK_W5100 EthernetUDP *udp; -#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 +#elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32 WiFiUDP *udp; #endif bool _daylight; ///< Does this time zone have daylight saving? From 102a9c7c5d0def480cdb6b5cb54ff1fd6a6a78a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Thu, 28 Dec 2017 00:20:24 +0100 Subject: [PATCH 23/30] Start ESP32 example --- examples/NTPClientESP32/NTPClientESP32.ino | 148 +++++++++++++++++++++ examples/NTPClientESP32/WifiConfigGM.h | 8 ++ 2 files changed, 156 insertions(+) create mode 100644 examples/NTPClientESP32/NTPClientESP32.ino create mode 100644 examples/NTPClientESP32/WifiConfigGM.h diff --git a/examples/NTPClientESP32/NTPClientESP32.ino b/examples/NTPClientESP32/NTPClientESP32.ino new file mode 100644 index 0000000..5bae0be --- /dev/null +++ b/examples/NTPClientESP32/NTPClientESP32.ino @@ -0,0 +1,148 @@ +/* +Copyright 2016 German Martin (gmag11@gmail.com). All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are +permitted provided that the following conditions are met : + +1. Redistributions of source code must retain the above copyright notice, this list of +conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, this list +of conditions and the following disclaimer in the documentation and / or other materials +provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY ''AS IS'' AND ANY EXPRESS OR IMPLIED +WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR +CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + The views and conclusions contained in the software and documentation are those of the + authors and should not be interpreted as representing official policies, either expressed + or implied, of German Martin +*/ + +/* + Name: NtpClient.ino + Created: 20/08/2016 + Author: gmag11@gmail.com + Editor: http://www.visualmicro.com +*/ + +#include +#include "WifiConfig.h" +#include +#include + +#ifndef WIFI_CONFIG_H +#define YOUR_WIFI_SSID "YOUR_WIFI_SSID" +#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" +#endif // !WIFI_CONFIG_H + +#define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 + +int8_t timeZone = 1; +int8_t minutesTimeZone = 0; +bool wifiFirstConnected = false; + +void onSTAConnected (WiFiEventStationModeConnected ipInfo) { + Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str()); +} + + +// Start NTP only after IP network is connected +void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { + Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); + Serial.printf ("Connected: %s\r\n", WiFi.status() == WL_CONNECTED? "yes" : "no"); + digitalWrite(ONBOARDLED, LOW); // Turn on LED + wifiFirstConnected = true; +} + +// Manage network disconnection +void onSTADisconnected(WiFiEventStationModeDisconnected event_info) { + Serial.printf("Disconnected from SSID: %s\n", event_info.ssid.c_str()); + Serial.printf("Reason: %d\n", event_info.reason); + digitalWrite(ONBOARDLED, HIGH); // Turn off LED + //NTP.stop(); // NTP sync can be disabled to avoid sync errors +} + +void processSyncEvent(NTPSyncEvent_t ntpEvent) { + if (ntpEvent) { + Serial.print("Time Sync error: "); + if (ntpEvent == noResponse) + Serial.println("NTP server not reachable"); + else if (ntpEvent == invalidAddress) + Serial.println("Invalid NTP server address"); + } + else { + Serial.print("Got NTP time: "); + Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); + } +} + +boolean syncEventTriggered = false; // True if a time even has been triggered +NTPSyncEvent_t ntpEvent; // Last triggered event + +void setup() +{ + static WiFiEventHandler e1, e2, e3; + + Serial.begin(115200); + Serial.println(); + WiFi.mode(WIFI_STA); + WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + + pinMode(ONBOARDLED, OUTPUT); // Onboard LED + digitalWrite(ONBOARDLED, HIGH); // Switch off LED + + NTP.onNTPSyncEvent([](NTPSyncEvent_t event) { + ntpEvent = event; + syncEventTriggered = true; + }); + + // Deprecated + /*WiFi.onEvent([](WiFiEvent_t e) { + Serial.printf("Event wifi -----> %d\n", e); + });*/ + + e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client + e2 = WiFi.onStationModeDisconnected(onSTADisconnected); + e3 = WiFi.onStationModeConnected (onSTAConnected); +} + +void loop() +{ + static int i = 0; + static int last = 0; + + if (wifiFirstConnected) { + wifiFirstConnected = false; + NTP.begin ("pool.ntp.org", timeZone, true, minutesTimeZone); + NTP.setInterval (63); + } + + if (syncEventTriggered) { + processSyncEvent(ntpEvent); + syncEventTriggered = false; + } + + if ((millis() - last) > 5100) { + //Serial.println(millis() - last); + last = millis(); + Serial.print(i); Serial.print(" "); + Serial.print(NTP.getTimeDateString()); Serial.print(" "); + Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); + Serial.print("WiFi is "); + Serial.print(WiFi.isConnected() ? "connected" : "not connected"); Serial.print(". "); + Serial.print("Uptime: "); + Serial.print(NTP.getUptimeString()); Serial.print(" since "); + Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); + + i++; + } + delay(0); +} diff --git a/examples/NTPClientESP32/WifiConfigGM.h b/examples/NTPClientESP32/WifiConfigGM.h new file mode 100644 index 0000000..a593bee --- /dev/null +++ b/examples/NTPClientESP32/WifiConfigGM.h @@ -0,0 +1,8 @@ +#pragma once +#ifndef WIFI_CONFIG_H +#define WIFI_CONFIG_H + +#define YOUR_WIFI_SSID "Virus_Detected!!!" +#define YOUR_WIFI_PASSWD "LaJunglaSigloXX1@." + +#endif //WIFI_CONFIG_H \ No newline at end of file From b3b0ca81ad0138091122fdfe06a1b84be7bd51d4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Thu, 28 Dec 2017 16:52:05 +0100 Subject: [PATCH 24/30] Finish ESP32 example --- examples/NTPClientESP32/NTPClientESP32.ino | 50 +++++++++++----------- 1 file changed, 24 insertions(+), 26 deletions(-) diff --git a/examples/NTPClientESP32/NTPClientESP32.ino b/examples/NTPClientESP32/NTPClientESP32.ino index 5bae0be..16536ab 100644 --- a/examples/NTPClientESP32/NTPClientESP32.ino +++ b/examples/NTPClientESP32/NTPClientESP32.ino @@ -34,7 +34,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G */ #include -#include "WifiConfig.h" +#include "WifiConfigGM.h" #include #include @@ -43,31 +43,32 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G #define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" #endif // !WIFI_CONFIG_H -#define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 +#define ONBOARDLED 5 // Built in LED on ESP-12/ESP-07 int8_t timeZone = 1; int8_t minutesTimeZone = 0; bool wifiFirstConnected = false; -void onSTAConnected (WiFiEventStationModeConnected ipInfo) { - Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str()); -} - - -// Start NTP only after IP network is connected -void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { - Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); - Serial.printf ("Connected: %s\r\n", WiFi.status() == WL_CONNECTED? "yes" : "no"); - digitalWrite(ONBOARDLED, LOW); // Turn on LED - wifiFirstConnected = true; -} - -// Manage network disconnection -void onSTADisconnected(WiFiEventStationModeDisconnected event_info) { - Serial.printf("Disconnected from SSID: %s\n", event_info.ssid.c_str()); - Serial.printf("Reason: %d\n", event_info.reason); - digitalWrite(ONBOARDLED, HIGH); // Turn off LED - //NTP.stop(); // NTP sync can be disabled to avoid sync errors +void onEvent (system_event_id_t event, system_event_info_t info) { + Serial.printf ("[WiFi-event] event: %d\n", event); + + switch (event) { + case SYSTEM_EVENT_STA_CONNECTED: + Serial.printf ("Connected to %s\r\n", info.connected.ssid); + break; + case SYSTEM_EVENT_STA_GOT_IP: + Serial.printf ("Got IP: %s\r\n", IPAddress(info.got_ip.ip_info.ip.addr).toString().c_str()); + Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); + digitalWrite (ONBOARDLED, LOW); // Turn on LED + wifiFirstConnected = true; + break; + case SYSTEM_EVENT_STA_DISCONNECTED: + Serial.printf ("Disconnected from SSID: %s\n", info.disconnected.ssid); + Serial.printf ("Reason: %d\n", info.disconnected.reason); + digitalWrite (ONBOARDLED, HIGH); // Turn off LED + //NTP.stop(); // NTP sync can be disabled to avoid sync errors + break; + } } void processSyncEvent(NTPSyncEvent_t ntpEvent) { @@ -89,8 +90,6 @@ NTPSyncEvent_t ntpEvent; // Last triggered event void setup() { - static WiFiEventHandler e1, e2, e3; - Serial.begin(115200); Serial.println(); WiFi.mode(WIFI_STA); @@ -109,9 +108,8 @@ void setup() Serial.printf("Event wifi -----> %d\n", e); });*/ - e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client - e2 = WiFi.onStationModeDisconnected(onSTADisconnected); - e3 = WiFi.onStationModeConnected (onSTAConnected); + WiFi.onEvent (onEvent); + } void loop() From 0b00fc5ce078b0e7fa4221e146d3503c8f5356fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Sun, 31 Dec 2017 18:26:25 +0100 Subject: [PATCH 25/30] Fill wifi configuration --- examples/NTPClientESP32/NTPClientESP32.ino | 2 +- examples/NTPClientESP32/WifiConfigGM.h | 8 -------- 2 files changed, 1 insertion(+), 9 deletions(-) delete mode 100644 examples/NTPClientESP32/WifiConfigGM.h diff --git a/examples/NTPClientESP32/NTPClientESP32.ino b/examples/NTPClientESP32/NTPClientESP32.ino index 16536ab..16a7aa8 100644 --- a/examples/NTPClientESP32/NTPClientESP32.ino +++ b/examples/NTPClientESP32/NTPClientESP32.ino @@ -34,7 +34,7 @@ CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE G */ #include -#include "WifiConfigGM.h" +//#include "WifiConfig.h" #include #include diff --git a/examples/NTPClientESP32/WifiConfigGM.h b/examples/NTPClientESP32/WifiConfigGM.h deleted file mode 100644 index a593bee..0000000 --- a/examples/NTPClientESP32/WifiConfigGM.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#ifndef WIFI_CONFIG_H -#define WIFI_CONFIG_H - -#define YOUR_WIFI_SSID "Virus_Detected!!!" -#define YOUR_WIFI_PASSWD "LaJunglaSigloXX1@." - -#endif //WIFI_CONFIG_H \ No newline at end of file From 41f2e80c9c0ad048c4284eba86cea647790f2ffb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Sun, 31 Dec 2017 19:29:45 +0100 Subject: [PATCH 26/30] Compatibility fix for older versions calls --- src/NtpClientLib.h | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index 7933648..4a936df 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -147,14 +147,36 @@ class NTPClient{ */ bool setNtpServerName(String ntpServerName); bool setNtpServerName (char* ntpServerName); + + /** + * Sets NTP server name. DEPRECATED, only for compatibility with older versions + * @param[in] New NTP server name. + * @param[in] Server index (0-2). + * @param[out] True if everything went ok. + */ + bool setNtpServerName (String ntpServerName, int idx) { + if (idx < 0 || idx > 2) + return false; + return setNtpServerName (ntpServerName); + } /** * Gets NTP server name - * @param[in] Server index (0-2). * @param[out] NTP server name. */ String getNtpServerName(); char* getNtpServerNamePtr (); + + /** + * Gets NTP server name. DEPRECATED, only for compatibility with older versions + * @param[in] Server index (0-2). + * @param[out] NTP server name. + */ + String getNtpServerName (int idx) { + if (idx < 0 || idx > 2) + return ""; + return getNtpServerName (); + } /** * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. From 2add9465ce24aa482257ee8c1689099140d57175 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Tue, 16 Jan 2018 23:19:05 +0100 Subject: [PATCH 27/30] Correct admisible TimeZones. Thanx Thohell --- src/NTPClientLib.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index 5439d80..aa34d6a 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -76,7 +76,7 @@ char* NTPClient::getNtpServerNamePtr () { bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) { - if ((timeZone >= -11) && (timeZone <= 13) && (minutes >= -59) && (minutes <= 59)) { + if ((timeZone >= -12) && (timeZone <= 14) && (minutes >= -59) && (minutes <= 59)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; From 2617ec9d5fb578a6deb3e2526cc428266b02ff52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Tue, 16 Jan 2018 23:50:46 +0100 Subject: [PATCH 28/30] Code cleanup --- examples/NTPClientAvr/NTPClientAvr.ino | 81 ++- examples/NTPClientESP32/NTPClientESP32.ino | 125 +++-- .../NTPClientESP8266/NTPClientESP8266.ino | 153 +++--- .../NTPClientMKR1000/NTPClientMKR1000.ino | 83 ++- src/NTPClientLib.cpp | 56 +- src/NtpClientLib.h | 487 +++++++++--------- 6 files changed, 484 insertions(+), 501 deletions(-) diff --git a/examples/NTPClientAvr/NTPClientAvr.ino b/examples/NTPClientAvr/NTPClientAvr.ino index 6d545bc..d494850 100644 --- a/examples/NTPClientAvr/NTPClientAvr.ino +++ b/examples/NTPClientAvr/NTPClientAvr.ino @@ -43,54 +43,51 @@ or implied, of German Martin // Enter a MAC address for your controller below. // Newer Ethernet shields have a MAC address printed on a sticker on the shield byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 + 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 }; EthernetClient client; -void setup() -{ - Serial.begin(115200); - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // no point in carrying on, so do nothing forevermore: - for (;;) - ; - } - NTP.onNTPSyncEvent([](NTPSyncEvent_t error) { - if (error) { - Serial.print("Time Sync error: "); - if (error == noResponse) - Serial.println("NTP server not reachable"); - else if (error == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } - }); - NTP.begin("es.pool.ntp.org", 1, true); - NTP.setInterval(63); +void setup () { + Serial.begin (115200); + if (Ethernet.begin (mac) == 0) { + Serial.println ("Failed to configure Ethernet using DHCP"); + // no point in carrying on, so do nothing forevermore: + for (;;) + ; + } + NTP.onNTPSyncEvent ([](NTPSyncEvent_t error) { + if (error) { + Serial.print ("Time Sync error: "); + if (error == noResponse) + Serial.println ("NTP server not reachable"); + else if (error == invalidAddress) + Serial.println ("Invalid NTP server address"); + } else { + Serial.print ("Got NTP time: "); + Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ())); + } + }); + NTP.begin ("es.pool.ntp.org", 1, true); + NTP.setInterval (63); } -void loop() -{ - static int i = 0; - static int last = 0; +void loop () { + static int i = 0; + static int last = 0; - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(". "); - Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); + if ((millis () - last) > 5100) { + //Serial.println(millis() - last); + last = millis (); + Serial.print (i); Serial.print (" "); + Serial.print (NTP.getTimeDateString ()); Serial.print (". "); + Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. "); + Serial.print ("Uptime: "); + Serial.print (NTP.getUptimeString ()); Serial.print (" since "); + Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ()); - i++; - } - delay(0); - Ethernet.maintain(); // Check DHCP for renewal + i++; + } + delay (0); + Ethernet.maintain (); // Check DHCP for renewal } diff --git a/examples/NTPClientESP32/NTPClientESP32.ino b/examples/NTPClientESP32/NTPClientESP32.ino index 16a7aa8..f7a64f6 100644 --- a/examples/NTPClientESP32/NTPClientESP32.ino +++ b/examples/NTPClientESP32/NTPClientESP32.ino @@ -16,14 +16,14 @@ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABI FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - The views and conclusions contained in the software and documentation are those of the - authors and should not be interpreted as representing official policies, either expressed - or implied, of German Martin +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING +NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +The views and conclusions contained in the software and documentation are those of the +authors and should not be interpreted as representing official policies, either expressed +or implied, of German Martin */ /* @@ -57,7 +57,7 @@ void onEvent (system_event_id_t event, system_event_info_t info) { Serial.printf ("Connected to %s\r\n", info.connected.ssid); break; case SYSTEM_EVENT_STA_GOT_IP: - Serial.printf ("Got IP: %s\r\n", IPAddress(info.got_ip.ip_info.ip.addr).toString().c_str()); + Serial.printf ("Got IP: %s\r\n", IPAddress (info.got_ip.ip_info.ip.addr).toString ().c_str ()); Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); digitalWrite (ONBOARDLED, LOW); // Turn on LED wifiFirstConnected = true; @@ -71,51 +71,48 @@ void onEvent (system_event_id_t event, system_event_info_t info) { } } -void processSyncEvent(NTPSyncEvent_t ntpEvent) { - if (ntpEvent) { - Serial.print("Time Sync error: "); - if (ntpEvent == noResponse) - Serial.println("NTP server not reachable"); - else if (ntpEvent == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } +void processSyncEvent (NTPSyncEvent_t ntpEvent) { + if (ntpEvent) { + Serial.print ("Time Sync error: "); + if (ntpEvent == noResponse) + Serial.println ("NTP server not reachable"); + else if (ntpEvent == invalidAddress) + Serial.println ("Invalid NTP server address"); + } else { + Serial.print ("Got NTP time: "); + Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ())); + } } boolean syncEventTriggered = false; // True if a time even has been triggered NTPSyncEvent_t ntpEvent; // Last triggered event -void setup() -{ - Serial.begin(115200); - Serial.println(); - WiFi.mode(WIFI_STA); - WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); - - pinMode(ONBOARDLED, OUTPUT); // Onboard LED - digitalWrite(ONBOARDLED, HIGH); // Switch off LED - - NTP.onNTPSyncEvent([](NTPSyncEvent_t event) { - ntpEvent = event; - syncEventTriggered = true; - }); - - // Deprecated - /*WiFi.onEvent([](WiFiEvent_t e) { - Serial.printf("Event wifi -----> %d\n", e); - });*/ +void setup () { + Serial.begin (115200); + Serial.println (); + WiFi.mode (WIFI_STA); + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + + pinMode (ONBOARDLED, OUTPUT); // Onboard LED + digitalWrite (ONBOARDLED, HIGH); // Switch off LED + + NTP.onNTPSyncEvent ([](NTPSyncEvent_t event) { + ntpEvent = event; + syncEventTriggered = true; + }); + + // Deprecated + /*WiFi.onEvent([](WiFiEvent_t e) { + Serial.printf("Event wifi -----> %d\n", e); + });*/ WiFi.onEvent (onEvent); } -void loop() -{ - static int i = 0; - static int last = 0; +void loop () { + static int i = 0; + static int last = 0; if (wifiFirstConnected) { wifiFirstConnected = false; @@ -123,24 +120,24 @@ void loop() NTP.setInterval (63); } - if (syncEventTriggered) { - processSyncEvent(ntpEvent); - syncEventTriggered = false; - } - - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(" "); - Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); - Serial.print("WiFi is "); - Serial.print(WiFi.isConnected() ? "connected" : "not connected"); Serial.print(". "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); - - i++; - } - delay(0); + if (syncEventTriggered) { + processSyncEvent (ntpEvent); + syncEventTriggered = false; + } + + if ((millis () - last) > 5100) { + //Serial.println(millis() - last); + last = millis (); + Serial.print (i); Serial.print (" "); + Serial.print (NTP.getTimeDateString ()); Serial.print (" "); + Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. "); + Serial.print ("WiFi is "); + Serial.print (WiFi.isConnected () ? "connected" : "not connected"); Serial.print (". "); + Serial.print ("Uptime: "); + Serial.print (NTP.getUptimeString ()); Serial.print (" since "); + Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ()); + + i++; + } + delay (0); } diff --git a/examples/NTPClientESP8266/NTPClientESP8266.ino b/examples/NTPClientESP8266/NTPClientESP8266.ino index 3a8ee37..e43123d 100644 --- a/examples/NTPClientESP8266/NTPClientESP8266.ino +++ b/examples/NTPClientESP8266/NTPClientESP8266.ino @@ -16,14 +16,14 @@ WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABI FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.IN NO EVENT SHALL OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR - SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON - ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING - NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - - The views and conclusions contained in the software and documentation are those of the - authors and should not be interpreted as representing official policies, either expressed - or implied, of German Martin + SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON + ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING + NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + The views and conclusions contained in the software and documentation are those of the + authors and should not be interpreted as representing official policies, either expressed + or implied, of German Martin */ /* @@ -50,74 +50,71 @@ int8_t minutesTimeZone = 0; bool wifiFirstConnected = false; void onSTAConnected (WiFiEventStationModeConnected ipInfo) { - Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str()); + Serial.printf ("Connected to %s\r\n", ipInfo.ssid.c_str ()); } // Start NTP only after IP network is connected -void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { - Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); - Serial.printf ("Connected: %s\r\n", WiFi.status() == WL_CONNECTED? "yes" : "no"); - digitalWrite(ONBOARDLED, LOW); // Turn on LED +void onSTAGotIP (WiFiEventStationModeGotIP ipInfo) { + Serial.printf ("Got IP: %s\r\n", ipInfo.ip.toString ().c_str ()); + Serial.printf ("Connected: %s\r\n", WiFi.status () == WL_CONNECTED ? "yes" : "no"); + digitalWrite (ONBOARDLED, LOW); // Turn on LED wifiFirstConnected = true; } // Manage network disconnection -void onSTADisconnected(WiFiEventStationModeDisconnected event_info) { - Serial.printf("Disconnected from SSID: %s\n", event_info.ssid.c_str()); - Serial.printf("Reason: %d\n", event_info.reason); - digitalWrite(ONBOARDLED, HIGH); // Turn off LED - //NTP.stop(); // NTP sync can be disabled to avoid sync errors +void onSTADisconnected (WiFiEventStationModeDisconnected event_info) { + Serial.printf ("Disconnected from SSID: %s\n", event_info.ssid.c_str ()); + Serial.printf ("Reason: %d\n", event_info.reason); + digitalWrite (ONBOARDLED, HIGH); // Turn off LED + //NTP.stop(); // NTP sync can be disabled to avoid sync errors } -void processSyncEvent(NTPSyncEvent_t ntpEvent) { - if (ntpEvent) { - Serial.print("Time Sync error: "); - if (ntpEvent == noResponse) - Serial.println("NTP server not reachable"); - else if (ntpEvent == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } +void processSyncEvent (NTPSyncEvent_t ntpEvent) { + if (ntpEvent) { + Serial.print ("Time Sync error: "); + if (ntpEvent == noResponse) + Serial.println ("NTP server not reachable"); + else if (ntpEvent == invalidAddress) + Serial.println ("Invalid NTP server address"); + } else { + Serial.print ("Got NTP time: "); + Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ())); + } } boolean syncEventTriggered = false; // True if a time even has been triggered NTPSyncEvent_t ntpEvent; // Last triggered event -void setup() -{ - static WiFiEventHandler e1, e2, e3; - - Serial.begin(115200); - Serial.println(); - WiFi.mode(WIFI_STA); - WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); - - pinMode(ONBOARDLED, OUTPUT); // Onboard LED - digitalWrite(ONBOARDLED, HIGH); // Switch off LED - - NTP.onNTPSyncEvent([](NTPSyncEvent_t event) { - ntpEvent = event; - syncEventTriggered = true; - }); - - // Deprecated - /*WiFi.onEvent([](WiFiEvent_t e) { - Serial.printf("Event wifi -----> %d\n", e); - });*/ - - e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client - e2 = WiFi.onStationModeDisconnected(onSTADisconnected); +void setup () { + static WiFiEventHandler e1, e2, e3; + + Serial.begin (115200); + Serial.println (); + WiFi.mode (WIFI_STA); + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + + pinMode (ONBOARDLED, OUTPUT); // Onboard LED + digitalWrite (ONBOARDLED, HIGH); // Switch off LED + + NTP.onNTPSyncEvent ([](NTPSyncEvent_t event) { + ntpEvent = event; + syncEventTriggered = true; + }); + + // Deprecated + /*WiFi.onEvent([](WiFiEvent_t e) { + Serial.printf("Event wifi -----> %d\n", e); + });*/ + + e1 = WiFi.onStationModeGotIP (onSTAGotIP);// As soon WiFi is connected, start NTP Client + e2 = WiFi.onStationModeDisconnected (onSTADisconnected); e3 = WiFi.onStationModeConnected (onSTAConnected); } -void loop() -{ - static int i = 0; - static int last = 0; +void loop () { + static int i = 0; + static int last = 0; if (wifiFirstConnected) { wifiFirstConnected = false; @@ -125,24 +122,24 @@ void loop() NTP.setInterval (63); } - if (syncEventTriggered) { - processSyncEvent(ntpEvent); - syncEventTriggered = false; - } - - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(" "); - Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); - Serial.print("WiFi is "); - Serial.print(WiFi.isConnected() ? "connected" : "not connected"); Serial.print(". "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); - - i++; - } - delay(0); + if (syncEventTriggered) { + processSyncEvent (ntpEvent); + syncEventTriggered = false; + } + + if ((millis () - last) > 5100) { + //Serial.println(millis() - last); + last = millis (); + Serial.print (i); Serial.print (" "); + Serial.print (NTP.getTimeDateString ()); Serial.print (" "); + Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. "); + Serial.print ("WiFi is "); + Serial.print (WiFi.isConnected () ? "connected" : "not connected"); Serial.print (". "); + Serial.print ("Uptime: "); + Serial.print (NTP.getUptimeString ()); Serial.print (" since "); + Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ()); + + i++; + } + delay (0); } diff --git a/examples/NTPClientMKR1000/NTPClientMKR1000.ino b/examples/NTPClientMKR1000/NTPClientMKR1000.ino index 480dfcd..a229a2b 100644 --- a/examples/NTPClientMKR1000/NTPClientMKR1000.ino +++ b/examples/NTPClientMKR1000/NTPClientMKR1000.ino @@ -48,51 +48,48 @@ or implied, of German Martin #endif // !WIFI_CONFIG_H //WiFiClient client; -void setup() -{ - Serial.begin(115200); - WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); - while (WiFi.status() != WL_CONNECTED) { - Serial.print('.'); - delay(500); - } - Serial.println(); - NTP.onNTPSyncEvent([](NTPSyncEvent_t error) { - if (error) { - Serial.print("Time Sync error: "); - if (error == noResponse) - Serial.println("NTP server not reachable"); - else if (error == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } - }); - NTP.begin("pool.ntp.org", 1, true); - NTP.setInterval(63); +void setup () { + Serial.begin (115200); + WiFi.begin (YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); + while (WiFi.status () != WL_CONNECTED) { + Serial.print ('.'); + delay (500); + } + Serial.println (); + NTP.onNTPSyncEvent ([](NTPSyncEvent_t error) { + if (error) { + Serial.print ("Time Sync error: "); + if (error == noResponse) + Serial.println ("NTP server not reachable"); + else if (error == invalidAddress) + Serial.println ("Invalid NTP server address"); + } else { + Serial.print ("Got NTP time: "); + Serial.println (NTP.getTimeDateString (NTP.getLastNTPSync ())); + } + }); + NTP.begin ("pool.ntp.org", 1, true); + NTP.setInterval (63); } -void loop() -{ - static int i = 0; - static int last = 0; +void loop () { + static int i = 0; + static int last = 0; - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(" "); - Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); - Serial.print("WiFi is "); - - Serial.print((WiFi.status() == WL_CONNECTED) ? "connected" : "not connected"); Serial.print(". "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); + if ((millis () - last) > 5100) { + //Serial.println(millis() - last); + last = millis (); + Serial.print (i); Serial.print (" "); + Serial.print (NTP.getTimeDateString ()); Serial.print (" "); + Serial.print (NTP.isSummerTime () ? "Summer Time. " : "Winter Time. "); + Serial.print ("WiFi is "); - i++; - } - delay(0); + Serial.print ((WiFi.status () == WL_CONNECTED) ? "connected" : "not connected"); Serial.print (". "); + Serial.print ("Uptime: "); + Serial.print (NTP.getUptimeString ()); Serial.print (" since "); + Serial.println (NTP.getTimeDateString (NTP.getFirstSync ()).c_str ()); + + i++; + } + delay (0); } diff --git a/src/NTPClientLib.cpp b/src/NTPClientLib.cpp index aa34d6a..580386c 100644 --- a/src/NTPClientLib.cpp +++ b/src/NTPClientLib.cpp @@ -43,8 +43,7 @@ or implied, of German Martin NTPClient::NTPClient () { } -bool NTPClient::setNtpServerName(String ntpServerName) -{ +bool NTPClient::setNtpServerName (String ntpServerName) { char * name = (char *)malloc ((ntpServerName.length () + 1) * sizeof (char)); if (!name) return false; @@ -65,8 +64,7 @@ bool NTPClient::setNtpServerName (char* ntpServerName) { return true; } -String NTPClient::getNtpServerName() -{ +String NTPClient::getNtpServerName () { return String (_ntpServerName); } @@ -74,21 +72,20 @@ char* NTPClient::getNtpServerNamePtr () { return _ntpServerName; } -bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) -{ +bool NTPClient::setTimeZone (int8_t timeZone, int8_t minutes) { if ((timeZone >= -12) && (timeZone <= 14) && (minutes >= -59) && (minutes <= 59)) { // Temporarily set time to new time zone, before trying to synchronize int8_t timeDiff = timeZone - _timeZone; _timeZone = timeZone; _minutesOffset = minutes; - setTime(now() + timeDiff * SECS_PER_HOUR + minutes * SECS_PER_MIN); + setTime (now () + timeDiff * SECS_PER_HOUR + minutes * SECS_PER_MIN); if (udp && (timeStatus () != timeNotSet)) { setTime (getTime ()); } - DEBUGLOG("NTP time zone set to: %d\r\n", timeZone); - return true; - } - return false; + DEBUGLOG ("NTP time zone set to: %d\r\n", timeZone); + return true; + } + return false; } boolean sendNTPpacket (const char* address, UDP *udp) { @@ -108,9 +105,9 @@ boolean sendNTPpacket (const char* address, UDP *udp) { ntpPacketBuffer[14] = 49; ntpPacketBuffer[15] = 52; // all NTP fields have been given values, now - // you can send a packet requesting a timestamp: + // you can send a packet requesting a timestamp: udp->beginPacket (address, DEFAULT_NTP_PORT); //NTP requests are to port 123 - udp->write(ntpPacketBuffer, NTP_PACKET_SIZE); + udp->write (ntpPacketBuffer, NTP_PACKET_SIZE); udp->endPacket (); return true; } @@ -149,14 +146,14 @@ time_t NTPClient::getTime () { time_t timeValue = decodeNtpMessage (ntpPacketBuffer); setSyncInterval (getLongInterval ()); if (!_firstSync) { - // if (timeStatus () == timeSet) + // if (timeStatus () == timeSet) _firstSync = timeValue; } //getFirstSync (); // Set firstSync value if not set before DEBUGLOG ("Sync frequency set low\n"); udp->stop (); setLastNTPSync (timeValue); - DEBUGLOG ("Successful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str()); + DEBUGLOG ("Successful NTP sync at %s", getTimeDateString (getLastNTPSync ()).c_str ()); if (onSyncEvent) onSyncEvent (timeSyncd); @@ -171,11 +168,10 @@ time_t NTPClient::getTime () { setSyncInterval (getShortInterval ()); // Retry connection more often if (onSyncEvent) onSyncEvent (noResponse); - return 0; // return 0 if unable to get the time + return 0; // return 0 if unable to get the time } -int8_t NTPClient::getTimeZone() -{ +int8_t NTPClient::getTimeZone () { return _timeZone; } @@ -184,11 +180,11 @@ int8_t NTPClient::getTimeZoneMinutes () { } /*void NTPClient::setLastNTPSync(time_t moment) { - _lastSyncd = moment; + _lastSyncd = moment; }*/ -time_t NTPClient::s_getTime() { - return NTP.getTime(); +time_t NTPClient::s_getTime () { + return NTP.getTime (); } #if NETWORK_TYPE == NETWORK_W5100 @@ -240,7 +236,7 @@ bool NTPClient::setInterval (int interval) { if (interval >= 10) { if (_longInterval != interval) { _longInterval = interval; - DEBUGLOG ("Sync interval set to %d\n",interval); + DEBUGLOG ("Sync interval set to %d\n", interval); if (timeStatus () == timeSet) setSyncInterval (interval); } @@ -258,8 +254,8 @@ bool NTPClient::setInterval (int shortInterval, int longInterval) { } else { setSyncInterval (longInterval); } - DEBUGLOG ("Short sync interval set to %d\n",shortInterval); - DEBUGLOG ("Long sync interval set to %d\n",longInterval); + DEBUGLOG ("Short sync interval set to %d\n", shortInterval); + DEBUGLOG ("Long sync interval set to %d\n", longInterval); return true; } else return false; @@ -286,7 +282,7 @@ bool NTPClient::getDayLight () { String NTPClient::getTimeStr (time_t moment) { char timeStr[10]; sprintf (timeStr, "%02d:%02d:%02d", hour (moment), minute (moment), second (moment)); - + return timeStr; } @@ -331,7 +327,7 @@ String NTPClient::getUptimeString () { days = uptime / SECS_PER_DAY; char uptimeStr[20]; - sprintf (uptimeStr, "%d days %02d:%02d:%02d", days, hours, minutes, seconds); + sprintf (uptimeStr, "%4u days %02d:%02d:%02d", days, hours, minutes, seconds); return uptimeStr; } @@ -355,9 +351,9 @@ time_t NTPClient::getFirstSync () { bool NTPClient::summertime (int year, byte month, byte day, byte hour, byte tzHours) // input parameters: "normal time" for year, month, day, hour and tzHours (0=UTC, 1=MEZ) { - if ((month<3) || (month>10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez - if ((month>3) && (month<10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep - if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day)<(1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) + if ((month < 3) || (month > 10)) return false; // keine Sommerzeit in Jan, Feb, Nov, Dez + if ((month > 3) && (month < 10)) return true; // Sommerzeit in Apr, Mai, Jun, Jul, Aug, Sep + if (month == 3 && (hour + 24 * day) >= (1 + tzHours + 24 * (31 - (5 * year / 4 + 4) % 7)) || month == 10 && (hour + 24 * day) < (1 + tzHours + 24 * (31 - (5 * year / 4 + 1) % 7))) return true; else return false; @@ -395,4 +391,4 @@ time_t NTPClient::decodeNtpMessage (char *messageBuffer) { return timeTemp; } -NTPClient NTP; \ No newline at end of file +NTPClient NTP; diff --git a/src/NtpClientLib.h b/src/NtpClientLib.h index 4a936df..cc831a3 100644 --- a/src/NtpClientLib.h +++ b/src/NtpClientLib.h @@ -106,48 +106,48 @@ const int NTP_PACKET_SIZE = 48; // NTP time is in the first 48 bytes of message #endif // NETWORK_TYPE typedef enum { - timeSyncd, // Time successfully got from NTP server - noResponse, // No response from server - invalidAddress // Address not reachable + timeSyncd, // Time successfully got from NTP server + noResponse, // No response from server + invalidAddress // Address not reachable } NTPSyncEvent_t; #if defined ARDUINO_ARCH_ESP8266 || defined ARDUINO_ARCH_ESP32 #include -typedef std::function onSyncEvent_t; +typedef std::function onSyncEvent_t; #else -typedef void(*onSyncEvent_t)(NTPSyncEvent_t); +typedef void (*onSyncEvent_t)(NTPSyncEvent_t); #endif -class NTPClient{ +class NTPClient { public: - /** - * Construct NTP client. - */ + /** + * Construct NTP client. + */ NTPClient (); - /** - * Starts time synchronization. - * @param[in] NTP server name as String. - * @param[in] Time offset from UTC. - * @param[in] true if this time zone has dayligth saving. + /** + * Starts time synchronization. + * @param[in] NTP server name as String. + * @param[in] Time offset from UTC. + * @param[in] true if this time zone has dayligth saving. * @param[in] Minutes offset added to hourly offset (optional). * @param[in] UDP connection instance (optional). - * @param[out] true if everything went ok. - */ + * @param[out] true if everything went ok. + */ #if NETWORK_TYPE == NETWORK_W5100 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, EthernetUDP* udp_conn = NULL); #elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32 bool begin (String ntpServerName = DEFAULT_NTP_SERVER, int8_t timeOffset = DEFAULT_NTP_TIMEZONE, bool daylight = false, int8_t minutes = 0, WiFiUDP* udp_conn = NULL); #endif - /** - * Sets NTP server name. - * @param[in] New NTP server name. - * @param[out] True if everything went ok. - */ - bool setNtpServerName(String ntpServerName); + /** + * Sets NTP server name. + * @param[in] New NTP server name. + * @param[out] True if everything went ok. + */ + bool setNtpServerName (String ntpServerName); bool setNtpServerName (char* ntpServerName); - + /** * Sets NTP server name. DEPRECATED, only for compatibility with older versions * @param[in] New NTP server name. @@ -160,13 +160,13 @@ class NTPClient{ return setNtpServerName (ntpServerName); } - /** - * Gets NTP server name - * @param[out] NTP server name. - */ - String getNtpServerName(); + /** + * Gets NTP server name + * @param[out] NTP server name. + */ + String getNtpServerName (); char* getNtpServerNamePtr (); - + /** * Gets NTP server name. DEPRECATED, only for compatibility with older versions * @param[in] Server index (0-2). @@ -178,25 +178,25 @@ class NTPClient{ return getNtpServerName (); } - /** - * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. - * Kept in public section to allow direct NTP request. - * @param[out] Time in UNIX time format. - */ - time_t getTime(); - - /** - * Sets timezone. - * @param[in] New time offset in hours (-11 <= timeZone <= +13). - * @param[out] True if everything went ok. - */ - bool setTimeZone(int8_t timeZone, int8_t minutes = 0); - - /** - * Gets timezone. - * @param[out] Time offset in hours (plus or minus). - */ - int8_t getTimeZone(); + /** + * Starts a NTP time request to server. Returns a time in UNIX time format. Normally only called from library. + * Kept in public section to allow direct NTP request. + * @param[out] Time in UNIX time format. + */ + time_t getTime (); + + /** + * Sets timezone. + * @param[in] New time offset in hours (-11 <= timeZone <= +13). + * @param[out] True if everything went ok. + */ + bool setTimeZone (int8_t timeZone, int8_t minutes = 0); + + /** + * Gets timezone. + * @param[out] Time offset in hours (plus or minus). + */ + int8_t getTimeZone (); /** * Gets minutes fraction of timezone. @@ -204,159 +204,159 @@ class NTPClient{ */ int8_t getTimeZoneMinutes (); - /** - * Stops time synchronization. - * @param[out] True if everything went ok. - */ - bool stop(); - - /** - * Changes sync period. - * @param[in] New interval in seconds. - * @param[out] True if everything went ok. - */ - bool setInterval(int interval); - - /** - * Changes sync period in sync'd and not sync'd status. - * @param[in] New interval while time is not first adjusted yet, in seconds. - * @param[in] New interval for normal operation, in seconds. - * @param[out] True if everything went ok. - */ - bool setInterval(int shortInterval, int longInterval); - - /** - * Gets sync period. - * @param[out] Interval for normal operation, in seconds. - */ - int getInterval(); - - /** - * Changes sync period not sync'd status. - * @param[out] Interval while time is not first adjusted yet, in seconds. - */ - int getShortInterval(); - - /** - * Gets sync period. - * @param[out] Interval for normal operation in seconds. - */ - int getLongInterval() { return getInterval(); } - - /** - * Set daylight time saving option. - * @param[in] true is daylight time savings apply. - */ - void setDayLight(bool daylight); - - /** - * Get daylight time saving option. - * @param[out] true is daylight time savings apply. - */ - bool getDayLight(); - - /** - * Convert current time to a String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ + /** + * Stops time synchronization. + * @param[out] True if everything went ok. + */ + bool stop (); + + /** + * Changes sync period. + * @param[in] New interval in seconds. + * @param[out] True if everything went ok. + */ + bool setInterval (int interval); + + /** + * Changes sync period in sync'd and not sync'd status. + * @param[in] New interval while time is not first adjusted yet, in seconds. + * @param[in] New interval for normal operation, in seconds. + * @param[out] True if everything went ok. + */ + bool setInterval (int shortInterval, int longInterval); + + /** + * Gets sync period. + * @param[out] Interval for normal operation, in seconds. + */ + int getInterval (); + + /** + * Changes sync period not sync'd status. + * @param[out] Interval while time is not first adjusted yet, in seconds. + */ + int getShortInterval (); + + /** + * Gets sync period. + * @param[out] Interval for normal operation in seconds. + */ + int getLongInterval () { return getInterval (); } + + /** + * Set daylight time saving option. + * @param[in] true is daylight time savings apply. + */ + void setDayLight (bool daylight); + + /** + * Get daylight time saving option. + * @param[out] true is daylight time savings apply. + */ + bool getDayLight (); + + /** + * Convert current time to a String. + * @param[out] String constructed from current time. + * TODO: Add internationalization support + */ String getTimeStr () { return getTimeStr (now ()); } - /** - * Convert a time in UNIX format to a String representing time. - * @param[out] String constructed from current time. - * @param[in] time_t object to convert to extract time. - * TODO: Add internationalization support - */ - String getTimeStr(time_t moment); - - /** - * Convert current date to a String. - * @param[out] String constructed from current date. - * TODO: Add internationalization support - */ + /** + * Convert a time in UNIX format to a String representing time. + * @param[out] String constructed from current time. + * @param[in] time_t object to convert to extract time. + * TODO: Add internationalization support + */ + String getTimeStr (time_t moment); + + /** + * Convert current date to a String. + * @param[out] String constructed from current date. + * TODO: Add internationalization support + */ String getDateStr () { return getDateStr (now ()); } - /** - * Convert a time in UNIX format to a String representing its date. - * @param[out] String constructed from current date. - * @param[in] time_t object to convert to extract date. - * TODO: Add internationalization support - */ - String getDateStr(time_t moment); - - /** - * Convert current time and date to a String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ + /** + * Convert a time in UNIX format to a String representing its date. + * @param[out] String constructed from current date. + * @param[in] time_t object to convert to extract date. + * TODO: Add internationalization support + */ + String getDateStr (time_t moment); + + /** + * Convert current time and date to a String. + * @param[out] String constructed from current time. + * TODO: Add internationalization support + */ String getTimeDateString () { return getTimeDateString (now ()); } - /** - * Convert current time and date to a String. - * @param[in] time_t object to convert to String. - * @param[out] String constructed from current time. - * TODO: Add internationalization support - */ - String getTimeDateString(time_t moment); - - /** - * Gets last successful sync time in UNIX format. - * @param[out] Last successful sync time. 0 equals never. - */ - time_t getLastNTPSync(); - - /** - * Get uptime in human readable String format. - * @param[out] Uptime. - */ - String getUptimeString(); - - /** - * Get uptime in UNIX format, time since MCU was last rebooted. - * @param[out] Uptime. 0 equals never. - */ - time_t getUptime(); - - /** - * Get first boot time in UNIX format, time when MCU was last rebooted. - * @param[out] Uptime. 0 equals never. - */ - time_t getLastBootTime(); - - /** - * Get first successful synchronization time after boot. - * @param[out] First sync time. - */ - time_t getFirstSync(); - - /** - * Set a callback that triggers after a sync trial. - * @param[in] function with void(NTPSyncEvent_t) or std::function (only for ESP8266) - * NTPSyncEvent_t equals 0 is there is no error - */ - void onNTPSyncEvent(onSyncEvent_t handler); - - /** - * True if current time is inside DST period (aka. summer time). False otherwise of if NTP object has DST - * calculation disabled - * @param[out] True = summertime enabled and time in summertime period - * False = sumertime disabled or time ouside summertime period - */ - boolean isSummerTime() { - if (_daylight) - return isSummerTimePeriod(now()); - else - return false; - } - - /** - * True if given time is inside DST period (aka. summer time). False otherwise. - * @param[in] time to make the calculation with - * @param[out] True = time in summertime period - * False = time ouside summertime period - */ - boolean isSummerTimePeriod(time_t moment); + /** + * Convert current time and date to a String. + * @param[in] time_t object to convert to String. + * @param[out] String constructed from current time. + * TODO: Add internationalization support + */ + String getTimeDateString (time_t moment); + + /** + * Gets last successful sync time in UNIX format. + * @param[out] Last successful sync time. 0 equals never. + */ + time_t getLastNTPSync (); + + /** + * Get uptime in human readable String format. + * @param[out] Uptime. + */ + String getUptimeString (); + + /** + * Get uptime in UNIX format, time since MCU was last rebooted. + * @param[out] Uptime. 0 equals never. + */ + time_t getUptime (); + + /** + * Get first boot time in UNIX format, time when MCU was last rebooted. + * @param[out] Uptime. 0 equals never. + */ + time_t getLastBootTime (); + + /** + * Get first successful synchronization time after boot. + * @param[out] First sync time. + */ + time_t getFirstSync (); + + /** + * Set a callback that triggers after a sync trial. + * @param[in] function with void(NTPSyncEvent_t) or std::function (only for ESP8266) + * NTPSyncEvent_t equals 0 is there is no error + */ + void onNTPSyncEvent (onSyncEvent_t handler); + + /** + * True if current time is inside DST period (aka. summer time). False otherwise of if NTP object has DST + * calculation disabled + * @param[out] True = summertime enabled and time in summertime period + * False = sumertime disabled or time ouside summertime period + */ + boolean isSummerTime () { + if (_daylight) + return isSummerTimePeriod (now ()); + else + return false; + } + + /** + * True if given time is inside DST period (aka. summer time). False otherwise. + * @param[in] time to make the calculation with + * @param[out] True = time in summertime period + * False = time ouside summertime period + */ + boolean isSummerTimePeriod (time_t moment); protected: @@ -365,67 +365,66 @@ class NTPClient{ #elif NETWORK_TYPE == NETWORK_ESP8266 || NETWORK_TYPE == NETWORK_WIFI101 || NETWORK_TYPE == NETWORK_ESP32 WiFiUDP *udp; #endif - bool _daylight; ///< Does this time zone have daylight saving? + bool _daylight; ///< Does this time zone have daylight saving? int8_t _timeZone = 0; ///< Keep track of set time zone offset int8_t _minutesOffset = 0; ///< Minutes offset for time zones with decimal numbers char* _ntpServerName; ///< Name of NTP server on Internet or LAN int _shortInterval; ///< Interval to set periodic time sync until first synchronization. - int _longInterval; ///< Interval to set periodic time sync - time_t _lastSyncd = 0; ///< Stored time of last successful sync - time_t _firstSync = 0; ///< Stored time of first successful sync after boot - unsigned long _uptime = 0; ///< Time since boot - onSyncEvent_t onSyncEvent; ///< Event handler callback - - /** - * Function that gets time from NTP server and convert it to Unix time format - * @param[out] Time form NTP in Unix Time Format. - */ - static time_t s_getTime(); - - /** - * Calculates the daylight saving for a given date. - * @param[in] Year. - * @param[in] Month. - * @param[in] Day. - * @param[in] Hour. - * @param[in] Time zone offset. - * @param[out] true if date and time are inside summertime period. - */ - bool summertime(int year, byte month, byte day, byte hour, byte tzHours); - - /** - * Helper function to add leading 0 to hour, minutes or seconds if < 10. - * @param[in] Digit to evaluate the need of leading 0. - * @param[out] Result digit with leading 0 if needed. - */ - //String printDigits(int digits); + int _longInterval; ///< Interval to set periodic time sync + time_t _lastSyncd = 0; ///< Stored time of last successful sync + time_t _firstSync = 0; ///< Stored time of first successful sync after boot + unsigned long _uptime = 0; ///< Time since boot + onSyncEvent_t onSyncEvent; ///< Event handler callback + + /** + * Function that gets time from NTP server and convert it to Unix time format + * @param[out] Time form NTP in Unix Time Format. + */ + static time_t s_getTime (); + + /** + * Calculates the daylight saving for a given date. + * @param[in] Year. + * @param[in] Month. + * @param[in] Day. + * @param[in] Hour. + * @param[in] Time zone offset. + * @param[out] true if date and time are inside summertime period. + */ + bool summertime (int year, byte month, byte day, byte hour, byte tzHours); + + /** + * Helper function to add leading 0 to hour, minutes or seconds if < 10. + * @param[in] Digit to evaluate the need of leading 0. + * @param[out] Result digit with leading 0 if needed. + */ + //String printDigits(int digits); public: - /** - * Decode NTP response contained in buffer. - * @param[in] Pointer to message buffer. - * @param[out] Decoded time from message, 0 if error ocurred. - */ - time_t decodeNtpMessage(char *messageBuffer); - - /** - * Set last successful synchronization time. - * @param[out] Last sync time. - */ - void setLastNTPSync(time_t moment); + /** + * Decode NTP response contained in buffer. + * @param[in] Pointer to message buffer. + * @param[out] Decoded time from message, 0 if error ocurred. + */ + time_t decodeNtpMessage (char *messageBuffer); + + /** + * Set last successful synchronization time. + * @param[out] Last sync time. + */ + void setLastNTPSync (time_t moment); private: - /** - * Sends NTP request packet to given IP address. - * @param[in] NTP server's IP address. - * @param[out] True if everything went ok. - */ - //bool sendNTPpacket(IPAddress &address); + /** + * Sends NTP request packet to given IP address. + * @param[in] NTP server's IP address. + * @param[out] True if everything went ok. + */ + //bool sendNTPpacket(IPAddress &address); //#endif }; extern NTPClient NTP; #endif // _NtpClientLib_h - From ffab7d1c4f5b2acf1e5bbce0f5020f3ba5869bde Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 17 Jan 2018 00:12:36 +0100 Subject: [PATCH 29/30] Update Readme.md to describe latest changes --- README.md | 190 ++++-------------------------------------------------- 1 file changed, 14 insertions(+), 176 deletions(-) diff --git a/README.md b/README.md index bbda1de..8dcdf66 100644 --- a/README.md +++ b/README.md @@ -1,206 +1,44 @@ # NtpClientLib ## Introduction -There are some NTP client examples around. You can see some examples, like [this]. +There are some NTP client examples around. You can see some examples, like [this](https://www.arduino.cc/en/Tutorial/UdpNTPClient). In a device like ESP8266 or any Internet connected Arduino having NTP synchronization is well convenient. Using that example you can add NTP client to your projects but I was looking for a quicker way to add it, using something like NTPClient class. So I decided to do my own NTP client libary to sync ESP8266 time via WiFi using Arduino IDE. It can also be used on any ethernet or WiFi connected Arduino, although as I do not have any WiFi enabled arduino code is not tested. Testers are welcome. +Recently, I've added support for Arduino MKR1000 and ESP32. + ## Description -This is a NTP library to be able to get time from NTP server with my ESP8266s. Initial support for regular Arduino is available. Please test it and inform via GitHub. +This is a NTP library to be able to get time from NTP server with my connected microcontrollers. Support for regular **Arduino** with **ethernet** shield, **ESP8266**, **ESP32** and Arduino **MKR1000** is available. Please test it and inform via GitHub. -Using the library is fairly easy. A NTP object is created inside library. You may use default values by using `NTP.begin()` without parameters. After that, synchronization is done regularly without user intervention. Some parameters can be adjusted: server, sync frequency, time offset. +Using the library is fairly easy. A NTP singleton object is created inside library. You may use default values by using `NTP.begin()` without parameters. After that, synchronization is done regularly without user intervention. Some parameters can be adjusted: server, sync frequency, time offset. You don't need anything more. Time update is managed inside library so, after `NTP.begin()` no more calls to library are needed. -Update frequency is higher (every 15 seconds as default) until 1st successful sync is achieved. Since then, your own (or default 1800 seconds) adjusted period applies. There is a way to adjust both period if needed. +Update frequency is higher (every 15 seconds as default) until 1st successful sync is achieved. Since then, your own (or default 1800 seconds) adjusted period applies. There is a way to adjust both short and long sync period if needed. + +~~In order to reduce scketch size, ESP8266 version makes use of internal Espressif SDK routines that already implement SNTP protocol.~~ -In order to reduce scketch size, ESP8266 version makes use of internal Espressif SDK routines that already implement SNTP protocol. +In current version source code is the same for all platforms. There has been some interface changes during last update. Althoug I've tried to keep backwards compatibility you may find some discrepancies. Let me know so that I can correct it. This library includes an uptime log too. It counts number of seconds since scketch is started. It can be checked calling `NTP.getUptime()` or `NTP.getUptimeString()` for a human readable string. -Every time that local time is adjuste a `ntpEvent` is thrown. You can attach a function to it using `NTP.onNTPSyncEvent()`. Indeed, this event is thrown just before time is sent to [Time] Libary. Bacause of that, you should try not to make time consuming tasks inside event handler. Although it is taken into account inside library, it would add some offset to calculated time. +Every time that local time is adjuste a `ntpEvent` is thrown. You can attach a function to it using `NTP.onNTPSyncEvent()`. Indeed, this event is thrown just before time is sent to [Time] Libary. Bacause of that, you should try not to make time consuming tasks inside event handler. Although it is taken into account inside library, it would add some offset to calculated time. My recommendation is to use a flag and process it inside `loop()`function. Called funtion format must be like `void eventHandler(NTPSyncEvent_t event)`. ESP8266 example uses a simple function to turn a flag on, so actual event handling code is run inside main loop. -## Example for Arduino - -```Arduino -#include -#include -#include -#include -#include -#include -#include - -// Enter a MAC address for your controller below. -// Newer Ethernet shields have a MAC address printed on a sticker on the shield -byte mac[] = { - 0x00, 0xAA, 0xBB, 0xCC, 0xDE, 0x02 -}; - -EthernetClient client; - -void setup() -{ - Serial.begin(115200); - if (Ethernet.begin(mac) == 0) { - Serial.println("Failed to configure Ethernet using DHCP"); - // no point in carrying on, so do nothing forevermore: - for (;;) - ; - } - NTP.onNTPSyncEvent([](NTPSyncEvent_t error) { - if (error) { - Serial.print("Time Sync error: "); - if (error == noResponse) - Serial.println("NTP server not reachable"); - else if (error == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } - }); - NTP.begin("es.pool.ntp.org", 1, true); - NTP.setInterval(63); -} - -void loop() -{ - static int i = 0; - static int last = 0; - - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(". "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); - - i++; - } - delay(0); - Ethernet.maintain(); // Check DHCP for renewal -} -``` - -## Example for ESP8266 - -```Arduino -#include -#include "WifiConfig.h" -#include -#include - -#ifndef WIFI_CONFIG_H -#define YOUR_WIFI_SSID "YOUR_WIFI_SSID" -#define YOUR_WIFI_PASSWD "YOUR_WIFI_PASSWD" -#endif // !WIFI_CONFIG_H - -#define ONBOARDLED 2 // Built in LED on ESP-12/ESP-07 - -// Start NTP only after IP network is connected -void onSTAGotIP(WiFiEventStationModeGotIP ipInfo) { - Serial.printf("Got IP: %s\r\n", ipInfo.ip.toString().c_str()); - NTP.begin("pool.ntp.org", 1, true); - NTP.setInterval(63); - digitalWrite(ONBOARDLED, LOW); // Turn on LED -} - -// Manage network disconnection -void onSTADisconnected(WiFiEventStationModeDisconnected event_info) { - Serial.printf("Disconnected from SSID: %s\n", event_info.ssid.c_str()); - Serial.printf("Reason: %d\n", event_info.reason); - digitalWrite(ONBOARDLED, HIGH); // Turn off LED - //NTP.stop(); // NTP sync can be disabled to avoid sync errors -} - -void processSyncEvent(NTPSyncEvent_t ntpEvent) { - if (ntpEvent) { - Serial.print("Time Sync error: "); - if (ntpEvent == noResponse) - Serial.println("NTP server not reachable"); - else if (ntpEvent == invalidAddress) - Serial.println("Invalid NTP server address"); - } - else { - Serial.print("Got NTP time: "); - Serial.println(NTP.getTimeDateString(NTP.getLastNTPSync())); - } -} - -boolean syncEventTriggered = false; // True if a time even has been triggered -NTPSyncEvent_t ntpEvent; // Last triggered event - -void setup() -{ - static WiFiEventHandler e1, e2; - - Serial.begin(115200); - WiFi.mode(WIFI_STA); - WiFi.begin(YOUR_WIFI_SSID, YOUR_WIFI_PASSWD); - - pinMode(ONBOARDLED, OUTPUT); // Onboard LED - digitalWrite(ONBOARDLED, HIGH); // Switch off LED - - NTP.onNTPSyncEvent([](NTPSyncEvent_t event) { - ntpEvent = event; - syncEventTriggered = true; - }); - - // Deprecated - /*WiFi.onEvent([](WiFiEvent_t e) { - Serial.printf("Event wifi -----> %d\n", e); - });*/ - - e1 = WiFi.onStationModeGotIP(onSTAGotIP);// As soon WiFi is connected, start NTP Client - e2 = WiFi.onStationModeDisconnected(onSTADisconnected); - -} - -void loop() -{ - static int i = 0; - static int last = 0; - - if (syncEventTriggered) { - processSyncEvent(ntpEvent); - syncEventTriggered = false; - } - - if ((millis() - last) > 5100) { - //Serial.println(millis() - last); - last = millis(); - Serial.print(i); Serial.print(" "); - Serial.print(NTP.getTimeDateString()); Serial.print(" "); - Serial.print(NTP.isSummerTime() ? "Summer Time. " : "Winter Time. "); - Serial.print("WiFi is "); - Serial.print(WiFi.isConnected() ? "connected" : "not connected"); Serial.print(". "); - Serial.print("Uptime: "); - Serial.print(NTP.getUptimeString()); Serial.print(" since "); - Serial.println(NTP.getTimeDateString(NTP.getFirstSync()).c_str()); - - i++; - } - delay(0); -} -``` +## Examples + +Please check examples folder into repository source code. ## Performance Don't expect atomic-clock-like precission. This library does not take network delay into account neither uses all NTP mechanisms available to improve accuracy. It is in the range of 1 to 2 seconds. Enough for most projects. -Next major update will add network delay compensation. Due to limited Time Library precission of 1 second, it probably will not affect overall accuracy. +I have the plan to add full network delay compensation. Due to limited Time Library precission of 1 second, it probably will not affect overall accuracy. ## Dependencies This library makes use of [Time](https://github.com/PaulStoffregen/Time.git) library. You need to add it to use NTPClientLib -_________________________________________________________ -[ntpClient.ino](https://github.com/esp8266/Arduino/tree/master/libraries/ESP8266WiFi/examples/NTPClient) is an example of how this library works. It shows current time and uptime every 5 seconds as soon it gets synchronized. From a9fc26936629c8f4e4c0587aa16684c6b31dcc02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Germ=C3=A1n=20Mart=C3=ADn?= Date: Wed, 17 Jan 2018 00:12:54 +0100 Subject: [PATCH 30/30] Update library infor for version 2.5.0 --- library.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/library.properties b/library.properties index dfa4e50..4db2b5b 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=NtpClientLib -version=2.0.5 +version=2.5.0 author=German Martin maintainer=German Martin sentence=Ntp Client Library