// Topik 14 – Pengenalan dan Praktikum REST API
// C. Praktik REST API dengan Thingspeak

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

WiFiClient espDewa;
const int dht_pin = 15;
DHTesp dhtSensor;

String thingSpeakAddress = "https://api.thingspeak.com";
String writeAPIKey = "9Y751Q3QMAFLJV2S";
String tsfield1Name = "field1";
String tsfield2Name = "field2";
String request_string_suhu;
String request_string_hum;

// Write API Key 9Y751Q3QMAFLJV2S
// Read API Keys G0WJZ4RFKVABI8P4

void setup() {
  // put your setup code here, to run once:
  Serial.begin(9600);
  Serial.println("Topik 14 – Pengenalan dan Praktikum REST API");
  WiFi.disconnect();
  WiFi.begin("Wokwi-GUEST", "");
  while ((!(WiFi.status() == WL_CONNECTED))) {
    delay(300);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi Connected");
  Serial.println("IP Address: ");
  Serial.println(WiFi.localIP());
  dhtSensor.setup(dht_pin, DHTesp::DHT22);
}

void sendThingspeak(float suhu, float hum) {
  if (espDewa.connect("api.thingspeak.com", 80)) {

    request_string_suhu = "/update?api_key=" + writeAPIKey + "&" + tsfield1Name + "=" + suhu;
    request_string_hum = "/update?api_key=" + writeAPIKey + "&" + tsfield2Name + "=" + hum;

    // Serial.println(String("GET ") + request_string_suhu + "HTTP/1.1\r\n" + 
    //                 "Host: " + thingSpeakAddress + "\r\n" +
    //                 "Connection: close\r\n\r\n");
    espDewa.print(String("GET ") + request_string_hum + "HTTP/1.1\r\n" + 
                    "Host: " + thingSpeakAddress + "\r\n" +
                    "Connection: close\r\n\r\n");
    delay(500);
    espDewa.print(String("GET ") + request_string_suhu + "HTTP/1.1\r\n" + 
                    "Host: " + thingSpeakAddress + "\r\n" +
                    "Connection: close\r\n\r\n");
    

    unsigned long timeout = millis();

    while (espDewa.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> ESP Dewa Timeout !");
        espDewa.stop();
        return;
      }
    }

    while (espDewa.available()) {
      String line = espDewa.readStringUntil('\r');
      Serial.print("Line: " + line);
    }

    Serial.println();
    Serial.println("Closing Connection");
  }
}

void loop() {
  // put your main code here, to run repeatedly:
  delay(2000); // this speeds up the simulation
  TempAndHumidity data = dhtSensor.getTempAndHumidity();

  float t = data.temperature;
  float h = data.humidity;

  sendThingspeak(t, h);

  if (isnan(h) || isnan(t)) {
    Serial.println("Failed to read from DHT22 sensor!");
    return;
  }
}