/*
modul NodeMCU ESP32 S
board Ai Thinker
TFT 1.8 ST7735 
rol de client pentru serverul Acces Point
ESP32 DHT11 Hall Oled AP
conectare afisaj
  LED       +3.3V
  SCK   GPIO 18
  SDA   GPIO 23
  RS/AO GPIO 2
  RESET GPIO 4
  CS    GPIO  5
  GND       GND
  Vcc       +3.3V

*/

#include <WiFi.h>
#include <HTTPClient.h>

const char* ssid = "ESP32-HotSpot";
const char* password = "12345678";

const char* serverNameTemp = "http://192.168.4.1/temperature";
const char* serverNameHumi = "http://192.168.4.1/humidity";

#include <Wire.h>
#include <XTronical_ST7735.h> // Hardware-specific library
#include <SPI.h>
#define TFT_DC      2 // register select (stands for Data Control perhaps!)
#define TFT_RST     4 // Display reset pin, you can also connect this to the ESP32 reset                          // in which case, set this #define pin to -1!
#define TFT_CS      5 // Display enable (Chip select), if not enabled will not talk on SPI bus
Adafruit_ST7735 tft = Adafruit_ST7735(TFT_CS,  TFT_DC, TFT_RST);  

String temperature;
String humidity;

unsigned long previousMillis = 0;
const long interval = 5000; 

void setup() {
  Serial.begin(115200);
  
  tft.init();   // initialize a ST7735S chip,
  tft.fillScreen(ST7735_RED);
  tft.setCursor(0, 0);
  tft.setTextColor(ST7735_WHITE);
  tft.setTextSize(2);
  tft.println("ESP32 Client");
  delay(5000);
  
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while(WiFi.status() != WL_CONNECTED) { 
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  tft.println("Connected");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
}

void loop() {
  unsigned long currentMillis = millis();
  
  if(currentMillis - previousMillis >= interval) {
     // Check WiFi connection status
    if(WiFi.status()== WL_CONNECTED ){ 
      temperature = httpGETRequest(serverNameTemp);
      humidity = httpGETRequest(serverNameHumi);
      Serial.println("Temperature: " + temperature + " *C - Humidity: " + humidity + " % ");
      
  tft.setTextWrap(false);
  tft.fillScreen(ST7735_BLACK);
  tft.setCursor(0, 0);
  tft.setTextColor(ST7735_YELLOW);
  tft.setTextSize(2);
  tft.println(temperature);
  tft.println(humidity);
      previousMillis = currentMillis;
    }
    else {
      Serial.println("WiFi Disconnected");
    }
  }
}

  String httpGETRequest(const char* serverName) {
  WiFiClient client;
  HTTPClient http;   
  http.begin(client, serverName);
  
  // Send HTTP POST request
  int httpResponseCode = http.GET();
  String payload = "--";  
  if (httpResponseCode>0) {
    Serial.print("HTTP Response code: ");
    Serial.println(httpResponseCode);
    payload = http.getString();
  }
  else {
    Serial.print("Error code: ");
    Serial.println(httpResponseCode);
  }
  http.end();
  return payload;
  }
