/*
  Free skecht.
  ESP32 NTP SERVER.
  FOR HEHUI ST7789 18-09-2023
*/

#include <Adafruit_GFX.h>    // Core graphics library
#include <Adafruit_ST7789.h> // Hardware-specific library for ST7789
#include <SPI.h>             // Arduino SPI library
#include <WiFi.h>
#include "time.h"

const char* ssid     = "your ssid";
const char* password = "your password";

const char* ntpServer = "pool.ntp.org";
const long  gmtOffset_sec = 3600;//0
const int   daylightOffset_sec = 3600;

// ST7789 TFT module connections
#define TFT_CS  15
#define TFT_DC   2
#define TFT_RST  4
#define TFT_SCL 18
#define TFT_SDA 23

// Initialize Adafruit ST7789 TFT library
Adafruit_ST7789 tft = Adafruit_ST7789(TFT_CS, TFT_DC, TFT_RST);

void setup(void) {
 Serial.begin(9600);
 Serial.println("");
 Serial.println("ESP32 NTP SERVER.");
 Serial.println("FOR HEHUI ST7789 18-09-2023");
 Serial.println("");
 // Connect to Wi-Fi
 Serial.print("Connecting to ");
 Serial.println(ssid);
 WiFi.begin(ssid, password);
 while (WiFi.status() != WL_CONNECTED) {
   delay(500);
   Serial.print(".");

   // if the display has CS pin try with SPI_MODE0// Was spi mode 2
   tft.init(240, 320, SPI_MODE2);// Init ST7789 display 240x320 pixel
   // if the screen is flipped, remove this command
   tft.setRotation(0);
   // text
   tft.fillScreen(ST77XX_RED);
   tft.invertDisplay(false);
   tft.setTextColor(ST77XX_YELLOW);
   tft.setTextSize(2);
   tft.setCursor(18, 10);
   tft.println("Esp32 NTP server.");
   tft.setCursor(18, 35);
   tft.println("For HEHUI ST7789.");
   delay(4000);
   tft.fillScreen(ST77XX_BLACK);

 }

 Serial.println("");
 Serial.println("WiFi connected.");
 // Init and get the time
 configTime(gmtOffset_sec, daylightOffset_sec, ntpServer);
 printLocalTime();

 //disconnect WiFi as it's no longer needed
 WiFi.disconnect(true);
 WiFi.mode(WIFI_OFF);
 delay(3000);
}
void loop() {
 delay(1000);
 printLocalTime();
}
void printLocalTime() {
 struct tm timeinfo;
 if (!getLocalTime(&timeinfo)) {
   Serial.println("Failed to obtain time");
   return;
 }
 //Serial.println(&timeinfo, "%A,  %d %B %Y %H:%M:%S");
 Serial.println("");
 Serial.println(&timeinfo, "%A,  %d %B %Y %H:%M");
 Serial.println("");
 tft.fillScreen(ST77XX_BLACK);
 tft.invertDisplay(false);
 tft.setTextColor(ST77XX_YELLOW);
 tft.setTextSize(2);
 tft.setCursor(85, 10);
 tft.println(&timeinfo, "%A");
 tft.setCursor(45, 35);
 tft.println(&timeinfo, "%d %B");
 tft.setCursor(95, 60);
 tft.setTextColor(ST77XX_GREEN);
 tft.println(&timeinfo, "%Y");
 tft.setTextColor(ST77XX_RED);