//libary rtc
#include "RTClib.h"

//libary lcd 20x2 i2c
#include "LiquidCrystal_I2C.h"

//libary Ultrasonic Sensor
#include "EasyUltrasonic.h"

//libary Wifi
#include  "WiFi.h"

//libary DHTesp
#include "DHTesp.h"

//membuat object
WiFiClient client;
EasyUltrasonic ultrasonic;
RTC_DS1307 rtc;
DHTesp dhtSensor;;
LiquidCrystal_I2C lcd(0x20, 20, 2);

//mendelkarasikan pin DHT dan Ultrasonic senosr
const int DHT_PIN = 15;
const int Trig = 19;
const int Echo = 23;


//membuat variabel thingspeak
String thingSpeakAddress = "api.thingspeak.com";
String writeAPIKey;
String tsfield1Name;
String request_string;

//membuat variabel hari rtc
char daysOfTheWeek[7][12] = {"Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jum'at", "Sabtu"};


void setup()
{
  lcd.init();
  lcd.backlight();
  Serial.begin(9600);
  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());
  //DHT sensor
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);
  //Ultrasonic
  ultrasonic.attach(Trig, Echo);

  //rtc
#ifndef ESP32
  while (!Serial);
#endif

  if (! rtc.begin()) {
    Serial.println("tidak bisa menemukan rtc");
    Serial.flush();
    abort();
  }

  if (! rtc.isrunning()) {
    Serial.println("RTC tidak berjalan, silahkan mengeset waktu");
  }
  rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));
}




void loop() {
  //Ultrasonic sensor
  float distanceCM = ultrasonic.getDistanceCM();
  Serial.print(distanceCM);
  Serial.println(" cm");

  //DHT sensor
  delay(1000);
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();

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

  kirim_thingspeak(t, h, distanceCM);

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

  //RTC
  DateTime now = rtc.now();

  Serial.print(now.year(), DEC);
  Serial.print('/');
  Serial.print(now.month(), DEC);
  Serial.print('/');
  Serial.print(now.day(), DEC);
  Serial.print(" (");
  Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
  Serial.print(") ");
  Serial.print(now.hour(), DEC);
  Serial.print(':');
  Serial.print(now.minute(), DEC);
  Serial.print(':');
  Serial.print(now.second(), DEC);
  Serial.println();

  Serial.print(" since midnight 1/1/1970 = ");
  Serial.print(now.unixtime());
  Serial.print("s = ");
  Serial.print(now.unixtime() / 86400L);
  Serial.println("d");

  // calculate a date which is 7 days, 12 hours, 30 minutes, and 6 seconds into the future
  DateTime future (now + TimeSpan(7, 12, 30, 6));

  lcd.setCursor(8, 0);
  Serial.print(" now + 7d + 12h + 30m + 6s: ");
  Serial.print(future.year(), DEC);
  Serial.print('/');
  Serial.print(future.month(), DEC);
  Serial.print('/');
  Serial.print(future.day(), DEC);
  Serial.print(' ');
  lcd.print(future.hour(), DEC);
  lcd.print(':');
  lcd.print(future.minute(), DEC);
  lcd.print(':');
  lcd.print(future.second(), DEC);
  Serial.println();

  Serial.println();

  lcd.setCursor(0, 0);
  lcd.print("Waktu = ");
  lcd.setCursor(0, 1);
  lcd.print("Suhu = ");
  lcd.setCursor(8, 1);
  lcd.print(t);
  lcd.setCursor(0, 2);
  lcd.print("Kelembapan = ");
  lcd.setCursor(14, 0);
  lcd.print(h);
  lcd.setCursor(0, 3);
  lcd.print("Jarak = ");
  lcd.setCursor(9, 3);
  lcd.print(distanceCM);
}

void kirim_thingspeak(float suhu, float hum, float distance) {
  if (client.connect("api.thingspeak.com", 80)) {
    request_string = "/update?";
    request_string += "key=";
    request_string += "Z1YVRVO3NGS8CAX0";
    request_string += "&";
    request_string += "field1";
    request_string += "=";
    request_string += suhu;
    request_string += "&";
    request_string += "field2";
    request_string += "=";
    request_string += hum;
    request_string += "&";
    request_string += "field3";
    request_string += "=";
    request_string += distance;






    Serial.println(String("GET ") + request_string + " HTTP/1.1\r\n" +
                   "Host: " + thingSpeakAddress + "\r\n" +
                   "Connection: close\r\n\r\n");

    client.print(String("GET ") + request_string + " HTTP/1.1\r\n" +
                 "Host: " + thingSpeakAddress + "\r\n" +
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
      if (millis() - timeout > 5000) {
        Serial.println(">>> Client Timeout !");
        client.stop();
        return;
      }
    }

    while (client.available()) {
      String line = client.readStringUntil('\r');
      Serial.print(line);
    }

    Serial.println();
    Serial.println("closing connection");

  }
}
GND5VSDASCLSQWRTCDS1307+