/*********
Rui Santos
Complete project details at https://randomnerdtutorials.com
Based on the NTP Client library example
*********/
#include "WiFi.h"
//#include "NTPClient.h"
#include <WiFiUdp.h>
#include "Arduino.h"
#include <Udp.h>
#define SEVENZYYEARS 2208988800UL
#define NTP_PACKET_SIZE 48
#define NTP_DEFAULT_LOCAL_PORT 1337
class NTPClient {
private:
UDP* _udp;
bool _udpSetup = false;
const char* _poolServerName = "pool.ntp.org"; // Default time server
IPAddress _poolServerIP;
int _port = NTP_DEFAULT_LOCAL_PORT;
long _timeOffset = 0;
// unsigned long _updateInterval = 60000; // In ms
unsigned long _currentEpoc = 0; // In s
unsigned long _lastUpdate = 0; // In ms
byte _packetBuffer[NTP_PACKET_SIZE];
void sendNTPPacket();
public:
NTPClient(UDP& udp);
NTPClient(UDP& udp, long timeOffset);
NTPClient(UDP& udp, const char* poolServerName);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset);
NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval);
NTPClient(UDP& udp, IPAddress poolServerIP);
NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset);
NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval);
unsigned long _updateInterval = 60000;
/**
* Set time server name
*
* @param poolServerName
*/
void setPoolServerName(const char* poolServerName);
/**
* Starts the underlying UDP client with the default local port
*/
void begin();
/**
* Starts the underlying UDP client with the specified local port
*/
void begin(int port);
/**
* This should be called in the main loop of your application. By default an update from the NTP Server is only
* made every 60 seconds. This can be configured in the NTPClient constructor.
*
* @return true on success, false on failure
*/
bool update();
/**
* This will force the update from the NTP Server.
*
* @return true on success, false on failure
*/
bool forceUpdate();
int getDay() const;
int getHours() const;
int getMinutes() const;
int getSeconds() const;
/**
* Changes the time offset. Useful for changing timezones dynamically
*/
void setTimeOffset(int timeOffset);
/**
* Set the update interval to another frequency. E.g. useful when the
* timeOffset should not be set in the constructor
*/
void setUpdateInterval(unsigned long updateInterval);
/**
* @return time formatted like `hh:mm:ss`
*/
String getFormattedTime() const;
String getFormattedDate();
String getFullFormattedTime() ;
/**
* @return time in seconds since Jan. 1, 1970
*/
unsigned long getEpochTime() const;
/**
* Stops the underlying UDP client
*/
void end();
};
NTPClient::NTPClient(UDP& udp) {
this->_udp = &udp;
}
NTPClient::NTPClient(UDP& udp, long timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName) {
this->_udp = &udp;
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP) {
this->_udp = &udp;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
}
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset){
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
}
NTPClient::NTPClient(UDP& udp, const char* poolServerName, long timeOffset, unsigned long updateInterval) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerName = poolServerName;
this->_updateInterval = updateInterval;
}
NTPClient::NTPClient(UDP& udp, IPAddress poolServerIP, long timeOffset, unsigned long updateInterval) {
this->_udp = &udp;
this->_timeOffset = timeOffset;
this->_poolServerIP = poolServerIP;
this->_poolServerName = NULL;
this->_updateInterval = updateInterval;
}
void NTPClient::begin() {
this->begin(NTP_DEFAULT_LOCAL_PORT);
}
void NTPClient::begin(int port) {
this->_port = port;
this->_udp->begin(this->_port);
this->_udpSetup = true;
}
bool NTPClient::forceUpdate() {
#ifdef DEBUG_NTPClient
Serial.println("Update from NTP Server");
#endif
// flush any existing packets
while(this->_udp->parsePacket() != 0)
this->_udp->flush();
this->sendNTPPacket();
// Wait till data is there or timeout...
byte timeout = 0;
int cb = 0;
do {
delay ( 10 );
cb = this->_udp->parsePacket();
if (timeout > 100) return false; // timeout after 1000 ms
timeout++;
} while (cb == 0);
this->_lastUpdate = millis() - (10 * (timeout + 1)); // Account for delay in reading the time
this->_udp->read(this->_packetBuffer, NTP_PACKET_SIZE);
unsigned long highWord = word(this->_packetBuffer[40], this->_packetBuffer[41]);
unsigned long lowWord = word(this->_packetBuffer[42], this->_packetBuffer[43]);
// combine the four bytes (two words) into a long integer
// this is NTP time (seconds since Jan 1 1900):
unsigned long secsSince1900 = highWord << 16 | lowWord;
this->_currentEpoc = secsSince1900 - SEVENZYYEARS;
return true; // return true after successful update
}
bool NTPClient::update() {
if ((millis() - this->_lastUpdate >= this->_updateInterval) // Update after _updateInterval
|| this->_lastUpdate == 0) { // Update if there was no update yet.
if (!this->_udpSetup) this->begin(); // setup the UDP client if needed
return this->forceUpdate();
}
return false; // return false if update does not occur
}
unsigned long NTPClient::getEpochTime() const {
return this->_timeOffset + // User offset
this->_currentEpoc + // Epoc returned by the NTP server
((millis() - this->_lastUpdate) / 1000); // Time since last update
}
int NTPClient::getDay() const {
return (((this->getEpochTime() / 86400L) + 4 ) % 7); //0 is Sunday
}
int NTPClient::getHours() const {
return ((this->getEpochTime() % 86400L) / 3600);
}
int NTPClient::getMinutes() const {
return ((this->getEpochTime() % 3600) / 60);
}
int NTPClient::getSeconds() const {
return (this->getEpochTime() % 60);
}
String NTPClient::getFormattedTime() const {
unsigned long rawTime = this->getEpochTime();
unsigned long hours = (rawTime % 86400L) / 3600;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
unsigned long minutes = (rawTime % 3600) / 60;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
unsigned long seconds = rawTime % 60;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return hoursStr + ":" + minuteStr + ":" + secondStr;
}
void NTPClient::end() {
this->_udp->stop();
this->_udpSetup = false;
}
void NTPClient::setTimeOffset(int timeOffset) {
this->_timeOffset = timeOffset;
}
void NTPClient::setUpdateInterval(unsigned long updateInterval) {
this->_updateInterval = updateInterval;
}
void NTPClient::setPoolServerName(const char* poolServerName) {
this->_poolServerName = poolServerName;
}
void NTPClient::sendNTPPacket() {
// set all bytes in the buffer to 0
memset(this->_packetBuffer, 0, NTP_PACKET_SIZE);
// Initialize values needed to form NTP request
// (see URL above for details on the packets)
this->_packetBuffer[0] = 0b11100011; // LI, Version, Mode
this->_packetBuffer[1] = 0; // Stratum, or type of clock
this->_packetBuffer[2] = 6; // Polling Interval
this->_packetBuffer[3] = 0xEC; // Peer Clock Precision
// 8 bytes of zero for Root Delay & Root Dispersion
this->_packetBuffer[12] = 49;
this->_packetBuffer[13] = 0x4E;
this->_packetBuffer[14] = 49;
this->_packetBuffer[15] = 52;
// all NTP fields have been given values, now
// you can send a packet requesting a timestamp:
if (this->_poolServerName) {
this->_udp->beginPacket(this->_poolServerName, 123);
} else {
this->_udp->beginPacket(this->_poolServerIP, 123);
}
this->_udp->write(this->_packetBuffer, NTP_PACKET_SIZE);
this->_udp->endPacket();
}
String NTPClient::getFormattedDate() {
time_t rawtime = this->getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
uint16_t year = ti->tm_year + 1900;
String yearStr = String(year);
uint8_t month = ti->tm_mon + 1;
String monthStr = month < 10 ? "0" + String(month) : String(month);
uint8_t day = ti->tm_mday;
String dayStr = day < 10 ? "0" + String(day) : String(day);
return yearStr + "-" + monthStr + "-" + dayStr;
}
String NTPClient::getFullFormattedTime() {
time_t rawtime = this->getEpochTime();
struct tm * ti;
ti = localtime (&rawtime);
uint16_t year = ti->tm_year + 1900;
String yearStr = String(year);
uint8_t month = ti->tm_mon + 1;
String monthStr = month < 10 ? "0" + String(month) : String(month);
uint8_t day = ti->tm_mday;
String dayStr = day < 10 ? "0" + String(day) : String(day);
uint8_t hours = ti->tm_hour;
String hoursStr = hours < 10 ? "0" + String(hours) : String(hours);
uint8_t minutes = ti->tm_min;
String minuteStr = minutes < 10 ? "0" + String(minutes) : String(minutes);
uint8_t seconds = ti->tm_sec;
String secondStr = seconds < 10 ? "0" + String(seconds) : String(seconds);
return yearStr + "-" + monthStr + "-" + dayStr + " " +
hoursStr + ":" + minuteStr + ":" + secondStr;
}
// Replace with your network credentials
const char ssid[] = "Wokwi-GUEST"; // your network SSID (name)
const char pass[] = ""; // your network password
// Define NTP Client to get time
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP);
bool LED=1;
int indY;
int indM;
int indD;
int indH;
int indS;
int indm;
// Variables to save date and time
String formattedDate;
String dayStamp;
String YearStamp;
String MonthStamp;
String HourStamp;
String MinStamp;
String SecStamp;
String timeStamp;
String formattedFullTime;
void setup() {
// Initialize Serial Monitor
Serial.begin(115200);
Serial.print("Connecting to ");
pinMode(2,OUTPUT);
Serial.println(ssid);
WiFi.begin(ssid,pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
// Print local IP address and start web server
Serial.println("");
Serial.println("WiFi connected.");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
// Initialize a NTPClient to get time
timeClient.begin();
// Set offset time in seconds to adjust for your timezone, for example:
// GMT +1 = 3600
// GMT +8 = 28800
// GMT -1 = -3600
// GMT 0 = 0
// timeClient._updateInterval=60000;
timeClient.setTimeOffset(3600);
}
void loop() {
digitalWrite(2,LED);
LED=1-LED;
delay(1000);
// update tous les 60 sec ici timeClient._updateInterval=60000; // In ms
if(timeClient.update()) {;
formattedFullTime=timeClient.getFullFormattedTime();
Serial.println(formattedFullTime);
// Extract date
indY=formattedFullTime.indexOf("-");
YearStamp=formattedFullTime.substring(0,indY);
indM=formattedFullTime.indexOf("-",indY+1);
MonthStamp=formattedFullTime.substring(indY+1,indM);
indD=formattedFullTime.indexOf(" ",indM+1);
dayStamp=formattedFullTime.substring(indM+1,indD);
indH=formattedFullTime.indexOf(":",indD+1);
HourStamp=formattedFullTime.substring(indD+1,indH);
indm=formattedFullTime.indexOf(":",indH+1);
MinStamp=formattedFullTime.substring(indH+1,indm);
SecStamp=formattedFullTime.substring(indm+1,indm+3);
// int splitT = formattedDate.indexOf("-");
// dayStamp = formattedDate.substring(0, splitT);
Serial.print("DATE: ");
Serial.println(dayStamp);
Serial.print("Month: ");
Serial.println(MonthStamp);
Serial.print("Year: ");
Serial.println(YearStamp);
Serial.print("Hour: ");
Serial.println(HourStamp);
Serial.print("Minute: ");
Serial.println(MinStamp);
Serial.print("seconde: ");
Serial.println(SecStamp);
}
// Extract time
// timeStamp = formattedDate.substring(splitT+1, formattedDate.length()-1);
// Serial.print("HOUR: ");
// Serial.println(timeStamp);
// delay(1000);
}