#include <ESP32Time.h>
#include <WiFi.h>
#include "time.h"
#include <ArduinoJson.h>
const char* ntpServer = "pool.ntp.org";
const long gmtOffset_sec = 25200;
const int daylightOffset_sec = 0;
//ESP32Time rtc;
ESP32Time rtc(0); // offset in seconds GMT+0
int pos = 0;
int neg = 0;
void setTime()
{
struct tm timeinfo;
Serial.print("Trying obtain time");
while(!getLocalTime(&timeinfo)){
Serial.print(".");
delay(250);
}
// Serial.println(&timeinfo, "%A, %B %d %Y %H:%M:%S");
int hour = timeinfo.tm_hour;
int minute = timeinfo.tm_min;
int sec = timeinfo.tm_sec;
int date = timeinfo.tm_mday;
int mounth = timeinfo.tm_mon + 1;
int year = timeinfo.tm_year + 1900;
if(hour >= 24){
hour = 0;
}
Serial.println();
Serial.print("hour: ");
Serial.println(hour);
Serial.print("min: ");
Serial.println(minute);
Serial.print("sec: ");
Serial.println(sec);
Serial.print("date: ");
Serial.println(date);
Serial.print("mon: ");
Serial.println(mounth);
Serial.print("year: ");
Serial.println(year);
// rtc.setTime(30, 24, 15, 17, 1, 2021); // 17th Jan 2021 15:24:30
rtc.setTime(sec, minute, hour, date, mounth, year);
}
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);
WiFi.begin("Wokwi-GUEST", "", 6);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println(" CONNECTED");
//init and get the time
configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
setTime();
//disconnect WiFi as it's no longer needed
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
}
void loop() {
// put your main code here, to run repeatedly:
StaticJsonDocument<256> doc;
doc["zone"] = "Zone 1";
doc["sensor_type"] = "Soil Moisture";
JsonObject timestamp = doc.createNestedObject("timestamp");
// timestamp["day"] = "Monday";
timestamp["date"] = rtc.getDay();
timestamp["month"] = rtc.getMonth() + 1;
timestamp["year"] = rtc.getYear();
timestamp["hour"] = rtc.getHour(true);
timestamp["minute"] = rtc.getMinute();
timestamp["sec"] = rtc.getSecond();
timestamp["epoch"] = rtc.getEpoch();
JsonObject data_value = doc.createNestedObject("data_value");
// data_value["day"] = "Monday";
data_value["value_1"] = pos++;
data_value["value_2"] = neg--;
// serializeJson(doc, Serial);
String jsonString;
serializeJson(doc, jsonString);
Serial.println(jsonString);
Serial.println("Complete");
delay(2000); // this speeds up the simulation
}