/*
  ESP32 HTTPClient Jokes API Example

  https://wokwi.com/projects/342032431249883731

  Copyright (C) 2022, Uri Shaked
*/

#include <ArduinoJson.h>
#include <Adafruit_GFX.h>
#include <Adafruit_ILI9341.h>
#include <DHT.h>
#include <WiFi.h>
#include <Wire.h>


#define NTP_SERVER     "pool.ntp.org"
#define UTC_OFFSET     1
#define UTC_OFFSET_DST 1

#define DHTPIN 13     
#define DHTTYPE DHT22
DHT dht(DHTPIN, DHTTYPE);

#define BTN_PIN 5
#define TFT_DC 2
#define TFT_CS 15
Adafruit_ILI9341 tft = Adafruit_ILI9341(TFT_CS, TFT_DC);



void measureTemp() {
  float temperature = dht.readTemperature();
  float humidity = dht.readHumidity();

  tft.setTextColor(ILI9341_WHITE);
  if (isnan(temperature) || isnan(humidity)) {
    tft.println(F("Failed to read from DHT sensor!"));
    return;
  }
  
  tft.setCursor(0, 0);
  tft.print(F("Humidity: "));
  tft.print(humidity);
  tft.print(F("%"));
  tft.setCursor(0, 20);
  tft.print(F("Temperature: "));
  tft.print(temperature);
  tft.write(0xF7);
  tft.print("C");
}

void spinner() {
  static int8_t counter = 0;
  const char* glyphs = "\xa1\xa5\xdb";
  tft.setCursor(15, 20);
  tft.print(glyphs[counter++]);
  if (counter == strlen(glyphs)) {
    counter = 0;
  }
}

void printLocalTime() {
  struct tm timeinfo;
  if (!getLocalTime(&timeinfo)) {
    tft.setCursor(0, 50);
    tft.println("Connection Err");
    return;
  }

  tft.setCursor(0, 50);
  tft.println(&timeinfo, "%H:%M");

  tft.setCursor(0, 70);
  tft.println(&timeinfo, "%d/%m/%Y");
}



void setup() {
  pinMode(BTN_PIN, INPUT_PULLUP);

  dht.begin();
  tft.begin();
  tft.setRotation(1);

  tft.setTextColor(ILI9341_WHITE);
  tft.setTextSize(2);

  tft.print("Connecting to ");
  tft.setCursor(0, 20);
  tft.print("WiFi ");

  WiFi.begin("Wokwi-GUEST", "", 6);
  while (WiFi.status() != WL_CONNECTED) {
    delay(250);
    spinner();
  }
  tft.fillScreen(ILI9341_BLACK);
  tft.println("WiFi connected");
  delay(250);
  tft.fillScreen(ILI9341_BLACK);

  configTime(UTC_OFFSET, UTC_OFFSET_DST, NTP_SERVER);
  setTimezone("CET-1CEST,M3.5.0,M10.5.0/3");
}

void loop() {
  measureTemp();
  printLocalTime();
  delay(2000);
  tft.fillScreen(ILI9341_BLACK);
}

void setTimezone(String timezone){
  Serial.printf("  Setting Timezone to %s\n",timezone.c_str());
  setenv("TZ",timezone.c_str(),1);  //  Now adjust the TZ.  Clock settings are adjusted to show the new local time
  tzset();
}
esp:0
esp:2
esp:4
esp:5
esp:12
esp:13
esp:14
esp:15
esp:16
esp:17
esp:18
esp:19
esp:21
esp:22
esp:23
esp:25
esp:26
esp:27
esp:32
esp:33
esp:34
esp:35
esp:3V3
esp:EN
esp:VP
esp:VN
esp:GND.1
esp:D2
esp:D3
esp:CMD
esp:5V
esp:GND.2
esp:TX
esp:RX
esp:GND.3
esp:D1
esp:D0
esp:CLK
lcd1:VCC
lcd1:GND
lcd1:CS
lcd1:RST
lcd1:D/C
lcd1:MOSI
lcd1:SCK
lcd1:LED
lcd1:MISO
btn1:1.l
btn1:2.l
btn1:1.r
btn1:2.r
dht1:VCC
dht1:SDA
dht1:NC
dht1:GND