#include <DHT.h>
#include <WiFi.h>
#include <HTTPClient.h>
#include <ThingSpeak.h> 
#define DHTPIN 15
#define DHTTYPE DHT22
#define SSID "Wokwi-GUEST"
#define PASS ""
#define WRITE_API_KEY "Y8TTXKVI2R3QD9JL"
#define READ_API_KEY "GACKHVQ27FZMO4L0"
#define CHANNEL_ID 2765310
#define THINGSPEAK_URL "http://api.thingspeak.com"
DHT dht(DHTPIN, DHTTYPE);
void setup() {
  Serial.begin(115200);
  dht.begin();
  Serial.print("Connecting to WiFi");
  WiFi.begin(SSID, PASS);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.print(".");
  }
  Serial.println("\nWiFi connected!");
}
void readDataFromThingSpeak() {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = THINGSPEAK_URL;
    url += "/channels/" + String(CHANNEL_ID) + 
           "/fields/1.json?api_key=" + String(READ_API_KEY) + 
           "&results=1";

    Serial.println("Fetching data from: " + url);
    http.begin(url);

    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
      String payload = http.getString();
      Serial.println("Received Data: " + payload);
    } else {
      Serial.print("Error in HTTP request: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  } else {
    Serial.println("WiFi not connected!");
  }
}

void loop() {
  // Read sensor data
  float temp = dht.readTemperature();
  float hum = dht.readHumidity();

  if (isnan(temp) || isnan(hum)) {
    Serial.println("Error reading data from DHT sensor!");
    return;
  }

  Serial.println("Temperature: " + String(temp) + "°C");
  Serial.println("Humidity: " + String(hum) + "%");

  // Write data to ThingSpeak
  writeDataToThingSpeak(temp, hum);

  // Read data back from ThingSpeak
  readDataFromThingSpeak();

  delay(20000); 
}

void writeDataToThingSpeak(float temp, float hum) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = THINGSPEAK_URL;
    url += "/update?api_key=" + String(WRITE_API_KEY) +
           "&field1=" + String(temp) + 
           "&field2=" + String(hum);

    Serial.println("Sending data to: " + url);
    http.begin(url);

    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
      Serial.print("Data sent successfully, HTTP Response code: ");
      Serial.println(httpResponseCode);
    } else {
      Serial.print("Error in HTTP request: ");
      Serial.println(httpResponseCode);
    }

    http.end();
  } else {
    Serial.println("WiFi not connected!");
  }
}