Hi all,
I am trying to get the current GMT time from an NTP server.
I connect to WiFi successfully using the WiFiManager Library GitHub - tzapu/WiFiManager: ESP8266 WiFi Connection manager with web captive portal
But I get this "date and time" returned:
Epoch Time: 14
Hour: 0
Minutes: 0
Seconds: 14
Week Day: 4
Month: 1
Year: 1970
Current date: 1970-01-04T00:00:14Z
Note that the numerals after the "T" increment (like a stopwatch)
Code:
#include <FS.h> //this needs to be first, or it all crashes and burns :)
#include <WiFiUdp.h>
#include <NTPClient.h>
#include <ESP8266WiFi.h>
#include <DNSServer.h>
#include <ESP8266WebServer.h>
#include <WiFiManager.h> //our library for managing credentials
#include <ArduinoJson.h>
/* DEFINE PARAMETERS FOR THE USER TO INPUT*/
char username[15]; //username
char password[20]; //password
const byte interruptPin = 0; //reset wifi credentials interrupt pin
bool shouldSaveConfig = false; //flag for saving data
bool inloop = false; //varaible to store if we are in the loop yet
/* CALLBACK TO NOTIFYING US OF THE NEED TO SAVE CONGIG */
void saveConfigCallback() {
Serial.println("Should save config");
shouldSaveConfig = true;
}
/* WIFIMANAGER */
WiFiManager wifiManager;
/* ADD AN INTERRUPT FOR RESETING ALL SAVED CREDENTIALS */
void ICACHE_RAM_ATTR Interrupt(); //attach an interrupt for reseting all credentials
/* DEFINE NTP CLIENT TO GET TIME */
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");
/* SETUP */
void setup() {
Serial.begin(115200);
Serial.println();
/* SETUP INTERRUPT PIN */
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), Interrupt, FALLING);
/* READ CONFIGURATION FROM FS JSON */
Serial.println("mounting FS...");
if (SPIFFS.begin()) {
Serial.println("mounted file system");
if (SPIFFS.exists("/config.json")) {
//file exists, reading and loading
Serial.println("reading config file");
File configFile = SPIFFS.open("/config.json", "r");
if (configFile) {
Serial.println("opened config file");
size_t size = configFile.size();
// Allocate a buffer to store contents of the file.
std::unique_ptr<char[]> buf(new char[size]);
configFile.readBytes(buf.get(), size);
DynamicJsonDocument json(1024);
auto deserializeError = deserializeJson(json, buf.get());
serializeJson(json, Serial);
/* IF YOU LOADED THE CONFIG FILE SUCCESSFULLY */
if (!deserializeError) {
Serial.println("\nparsed json");
strcpy(username, json["username"]);
strcpy(password, json["password"]);
Serial.println("Username");
Serial.println(username);
Serial.println("Password");
Serial.println(password);
}
/* IF YOU FAILED TO LOAD CONFIG FILE */
else {
Serial.println("failed to load json config");
}
configFile.close();
}
}
}
/* IF YOU FAILED TO LOAD FS JSON FILE */
else {
Serial.println("failed to mount FS");
} //end read
// The extra parameters to be configured (can be either global or just in the setup)
// After connecting, parameter.getValue() will get you the configured value
// id/name placeholder/prompt default length
/* ADD PARAMETERS FOR USER INPUT */
WiFiManagerParameter custom_username("username", "Username", username, 15); //input for Username
WiFiManagerParameter custom_password("password", "Password", password, 20); //input for Password
/* SET CONFIG SACE NOTIFY CALLBACK */
wifiManager.setSaveConfigCallback(saveConfigCallback);
/* SET STATIC IP */
wifiManager.setSTAStaticIPConfig(IPAddress(10, 0, 1, 99), IPAddress(10, 0, 1, 1), IPAddress(255, 255, 255, 0));
/* PARAMETERS */
wifiManager.addParameter(&custom_username); //for Username
wifiManager.addParameter(&custom_password); //for Password
/* TRY TO CONNECT TO WIFI WITH SSID AND PASSWORD, IF IT DOES NOT CONNECT IT STARTS AN ACCESS POINT WITH THE SPECIFIED NAME
AND GOES INTO A BLOCKING LOOP AWAITING CONFIGURATION */
if (!wifiManager.autoConnect("Credentials", "password")) {
Serial.println("failed to connect and hit timeout");
delay(3000);
//reset and try again, or maybe put it to deep sleep
ESP.reset();
delay(5000);
}
/* IF YOU GET HERE YOU HAVE CONNECTED TO WIFI */
Serial.println("Connected!");
/* READ THE UPDATED PARAMETERS */
strcpy(username, custom_username.getValue()); //Username
strcpy(password, custom_password.getValue()); //Password
/* SAVE THE CUSTOM PARAMETERS TO THE FS JSON FILE */
if (shouldSaveConfig) {
Serial.println("saving config");
DynamicJsonDocument json(1024);
json["username"] = username; //username
json["password"] = password; //password
/* IF YOU CAN'T OPEN THE JSON CONFIGURATION FILE */
File configFile = SPIFFS.open("/config.json", "w");
if (!configFile) {
Serial.println("failed to open config file for writing");
}
/* SERIAL PRINT WHAT THE JSON FILE CURRENTLY CONTAINS */
serializeJson(json, Serial);
serializeJson(json, configFile);
configFile.close();
//end save
}
Serial.println("local ip");
Serial.println(WiFi.localIP()); //print it's IP address
// Initialize a NTPClient to get time
timeClient.begin();
timeClient.setTimeOffset(0);
}
/* LOOP */
void loop() {
timeClient.update();
unsigned long epochTime = timeClient.getEpochTime();
Serial.print("Epoch Time: ");
Serial.println(epochTime);
int currentHour = timeClient.getHours();
Serial.print("Hour: ");
Serial.println(currentHour);
int currentMinute = timeClient.getMinutes();
Serial.print("Minutes: ");
Serial.println(currentMinute);
int currentSecond = timeClient.getSeconds();
Serial.print("Seconds: ");
Serial.println(currentSecond);
int currentDay = timeClient.getDay();
Serial.print("Week Day: ");
Serial.println(currentDay);
//Get a time structure
struct tm *ptm = gmtime ((time_t *)&epochTime);
int currentMonth = ptm->tm_mon + 1;
Serial.print("Month: ");
Serial.println(currentMonth);
int currentYear = ptm->tm_year + 1900;
Serial.print("Year: ");
Serial.println(currentYear);
//Print complete date:
String receivedTimeDate = (String(currentYear) + "-" + toStringAddZero(currentMonth) + "-" + toStringAddZero(currentDay)) + ("T") + (toStringAddZero(currentHour) + ":" + toStringAddZero(currentMinute) + ":" + toStringAddZero(currentSecond)) + ("Z");
Serial.print("Current date: ");
Serial.println(receivedTimeDate);
Serial.println("");
delay(2000);
}
String toStringAddZero(int data)
{
String st = "";
if (data < 10)
{
st = "0" + String(data);
}
else
{
st = String(data);
}
return st;
}
/* INTERRUPT */
void Interrupt() {
if (inloop == true) { //when the board first boots up unfortuantly it runs the interrupt and resets all our credentials, so we need to ensure that we are in the loop before the option to reset the credentials comes available
Serial.println("Resetting");
wifiManager.resetSettings(); //reset all saved credentials
ESP.reset(); //restart the ESP
}
}
Does anyone know what might be wrong?
Thanks very much,
Zeb