#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL3XvWT_aYr"
#define BLYNK_TEMPLATE_NAME "poject3"
#define BLYNK_AUTH_TOKEN "O6zkM7ErXBvIgU5jg5ztdcCtUCvDbuXA"

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include "DHTesp.h"

char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

#define LED1 13  // Merah
#define LED2 12  // Kuning
#define LED3 14  // Hijau
#define LED4 27
#define LED5 26


DHTesp dhtSensor;
const int DHT_PIN = 15;

#define Trig 18
#define Echo 19
float jarak = 0;
float ketinggian_air = 0;

//---widget lcd
WidgetLCD lcd(V20);
String inputText;
float latitude, longitude, altitude;

// baca jarak dari sensor ultra sonic
void baca_jarak()
{
  digitalWrite(Trig, LOW);
  delayMicroseconds(2);
  digitalWrite(Trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(Trig, LOW);

  int duration = pulseIn(Echo, HIGH);
  jarak = duration * 0.034 / 2;
  ketinggian_air = jarak;
}


void setup()
{
  dhtSensor.setup(DHT_PIN, DHTesp::DHT22);

  pinMode(LED1, OUTPUT);
  pinMode(LED2, OUTPUT);
  pinMode(LED3, OUTPUT);
  pinMode(LED4, OUTPUT);
  pinMode(LED5, OUTPUT);
  pinMode(Trig, OUTPUT);
  pinMode(Echo, INPUT);
  Serial.begin(9600);
  //Blynk.begin(auth, ssid, pass);
  Blynk.begin(auth, ssid, pass, "iot.serangkota.go.id", 8080);

  lcd.clear(); //Use it to clear the LCD Widget
  lcd.print(4, 0, "Hello"); // use: (position X: 0-15, position Y: 0-1, "Message you want to print")
  lcd.print(4, 1, "World");
  delay(1000);
  lcd.clear();
}

void loop()
{
  TempAndHumidity  data = dhtSensor.getTempAndHumidity();
  baca_jarak();
  Blynk.virtualWrite(V12, data.temperature);
  Blynk.virtualWrite(V13, data.humidity);
  Blynk.virtualWrite(V14, ketinggian_air);
  lcd.print(0, 0, "Temp:");
  lcd.print(6, 0, data.temperature);
  lcd.print(0, 1, "Hum :");
  lcd.print(6, 1, data.humidity);
  Blynk.run();
  timer.run();
  //Serial.println(latitude);
}


BLYNK_WRITE(V11) {
  latitude = param[0].asFloat();  // Membaca latitude
  longitude = param[1].asFloat(); // Membaca longitude
  altitude = param[2].asFloat();  // Membaca altitude (jika tersedia)

  // Tampilkan di Serial Monitor
  Serial.print("Latitude: ");
  Serial.println(latitude);
  Serial.print("Longitude: ");
  Serial.println(longitude);
  Serial.print("Altitude: ");
  Serial.println(altitude);
}

BLYNK_WRITE(V10) {
  inputText = param.asStr();  // Membaca teks dari widget Text Input
  Serial.print("Received Text: ");
  Serial.println(inputText);
}

BLYNK_WRITE (V0)
{
  digitalWrite(LED1, param.asInt());

}

BLYNK_WRITE (V1)
{
  digitalWrite(LED2, param.asInt());

}


BLYNK_WRITE (V2)
{
  digitalWrite(LED3, param.asInt());
}

BLYNK_WRITE (V3)
{
  digitalWrite(LED4, param.asInt());
}

BLYNK_WRITE (V4)
{
  digitalWrite(LED5, param.asInt());
}