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

const int DHT_PIN = 15;
const int LED_G_PIN = 2;
const int LED_R_PIN = 4;
const int LDR_PIN = 5;
const int BUZ_PIN = 18;

DHTesp dhtSensor;

char *ssid = "Wokwi-GUEST";
char *pass = "";

String serverName= "https://api.thingspeak.com/update?api_key=Z212V2ENTMK538P7";

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("Hello, ESP32!");
  pinMode(LDR_PIN, INPUT);
  pinMode(LED_G_PIN, OUTPUT);
  pinMode(LED_R_PIN, OUTPUT);
  pinMode(BUZ_PIN, OUTPUT);

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid,pass,6);

  while(WiFi.status() != WL_CONNECTED){
    Serial.print(".");
    delay(400);
  }

  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
}



void checkTemp(int temp, int humid){
  if(temp > 30){
  digitalWrite(LED_G_PIN ,HIGH);
  digitalWrite(LED_R_PIN, LOW);
  Serial.println("GREEN ON");
  }else{
    digitalWrite(LED_G_PIN ,LOW);
    digitalWrite(LED_R_PIN, HIGH);
    Serial.println("RED ON");
  }
}

void checkLight(double lumin){
  if (lumin == HIGH){ // check whether the lumin is on True or False
  Serial.println(lumin);
  Serial.println("DARK!");
  tone(BUZ_PIN, 1000); // Send 1KHz sound signal...


  } else if(lumin == LOW){
    Serial.println(lumin);
  Serial.println("LIGHT!");        // ...for 1 sec
  noTone(BUZ_PIN);     // Stop sound...
  
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  float temp = data.temperature;
  float humid = data.humidity;

  SendData(temp,humid,22);
  
  
  checkTemp(temp,humid);
  double lumin = digitalRead(LDR_PIN);
  checkLight(lumin);

  Serial.println("Temps: " + String(data.temperature, 2) + "°C");
  Serial.println("Humidity: " + String(data.humidity, 1) + "%");
  Serial.println("---");
  delay(2000); 
  delay(10); // this speeds up the simulation
}