//Smart relay with 2 mode (Manual & Automatic) Relay
// proses include library
#include <DHTesp.h>
#include <WiFi.h>
#include <HTTPClient.h>


// deklarasi variable
#define DHTPIN 13
#define LDRPIN A0
#define MOISTUREPIN A3

const char* ssid = "Wokwi-GUEST";
const char* password = "";

// url endpoint data of device
const char* serverName = "https://platform.antares.id:8080/~/antares-cse/antares-id/LatihanAntares_Permana/sensor-suhu";

// inisiasi object sensor
DHTesp dht;

int analogValue, Bbutton1, Mbutton1, Hbutton1; 
int nterkirim = 2;
int Bbutton = 4; //Menghidupkan Pompa
int Mbutton = 5; //Menghidupkan Lampu
int Hbutton = 18; //Untuk Mode Otomatis
int Bled = 19;
int Wled = 21;
int Pled = 22;
int variabel = 1;

float lux, voltage, resistance, hum, temp, moisture;

const float GAMMA = 0.7;
const float RL10 = 50;

// inisiasi variable
unsigned long lastTime = 0;
unsigned long timerDelay = 5000;

void setup() {
  // inisiasi interface serial
  Serial.begin(115200);

  // inisiasi sensor DHT
  dht.setup(DHTPIN, DHTesp::DHT22);

  // Menentukan pin
  pinMode(LDRPIN, INPUT);
  pinMode(nterkirim, OUTPUT);   // Atur pin LED biru sebagai output
  pinMode(Bled, OUTPUT);
  pinMode(Wled, OUTPUT);
  pinMode(Pled, OUTPUT);
  pinMode(MOISTUREPIN, INPUT);

  pinMode(Bbutton, INPUT);
  pinMode(Mbutton, INPUT);
  pinMode(Hbutton, INPUT);

  // inisiasi WiFi Client
  WiFi.begin(ssid, password);
  Serial.println("Connecting");
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.print("Connected to WiFi network with IP Address: ");
  Serial.println(WiFi.localIP());
  Serial.println("Timer set to 5 seconds (timerDelay variable), it will take 5 seconds before publishing the first reading.");
}

void sendsensor(){
  if ((millis() - lastTime) > timerDelay) {

    readsensor();

    if(WiFi.status() == WL_CONNECTED){
      WiFiClient client;
      HTTPClient http;

      // inisiasi komunikasi http
      http.begin(client, serverName);

      // inisiasi http header
      http.addHeader("X-M2M-Origin", "436d2f4387e63755:6b16fdc55123c588");
      http.addHeader("Content-Type", "application/json;ty=4");
      http.addHeader("Accept", "application/json");

      // inisiasi data yang dikirim di restful api
      String httpRequestData = "{\"m2m:cin\": { \"con\":\"{\\\"temp\\\":\\\"";
      httpRequestData += String(temp, 2);
      httpRequestData += "\\\",\\\"hum\\\":\\\"";
      httpRequestData += String(hum, 1);
      httpRequestData += "\\\",\\\"ldr\\\":\\\"";
      httpRequestData += String(lux, 2);
      httpRequestData += "\\\",\\\"Moisture\\\":\\\"";
      httpRequestData += String(moisture, 2);
      httpRequestData += "\\\",\\\"BButton\\\":\\\"";
      httpRequestData += String(Bbutton1);
      httpRequestData += "\\\",\\\"MButton\\\":\\\"";
      httpRequestData += String(Mbutton1);
      httpRequestData += "\\\",\\\"HButton\\\":\\\"";
      httpRequestData += String(Hbutton1);
      httpRequestData += "\\\"}\"}}";
      // mengirimkan HTTP POST request
      int httpResponseCode = http.POST(httpRequestData);
      
      Serial.print("HTTP Response code: ");
      Serial.println(httpResponseCode);
      if (httpResponseCode == 201) { digitalWrite(nterkirim, 1);} //notifikasi jika data berhasil terinput ke server
      else if (httpResponseCode != 201) { digitalWrite(nterkirim, 0);} //notifikasi jika data tidak berhasil terinput ke server
    // menutup koneksi
    http.end();
    }
    else{Serial.println("WiFi Disconnected");}
  lastTime = millis();
  }
}

void readsensor(){
    // baca suhu dan kelembapan dari sensor DHT22
    TempAndHumidity data = dht.getTempAndHumidity();

    // ekstrak data temperature
    temp = data.temperature;

    // ekstrak data humidity
    hum = data.humidity;

    Bbutton1 = digitalRead(Bbutton);
    Mbutton1 = digitalRead(Mbutton);
    Hbutton1 = digitalRead(Hbutton);

    // ekstrak data moisture
    moisture = analogRead(MOISTUREPIN);

    analogValue = analogRead(A0);
    analogValue = map(analogValue, 4095, 0, 1024, 0);
    voltage = analogValue / 1024. * 5;
    resistance = 2000 * voltage / (1 - voltage / 5);
    lux = pow(RL10 * 1e3 * pow(10, GAMMA) / resistance, (1 / GAMMA));

    // menampilkan data di serial
    Serial.println("Suhu: " + String(temp, 2) + "°C");
    Serial.println("Kelembaban: " + String(hum, 1) + "%");
    Serial.println("LDR: " + String(lux, 2) + "Lux");
    Serial.println("Moisture: " + String(moisture, 2) + "");
    Serial.println("BButton: " + String(Bbutton1) + "");
    Serial.println("MButton: " + String(Mbutton1) + "");
    Serial.println("HButton: " + String(Hbutton1) + "");
    Serial.println("---");
    nled();

    // waktu jeda sampling data
    // minimal 2 detik
    delay(5000);
}

void nled(){
    if (Bbutton1 == 1 ) {digitalWrite(Bled, HIGH);}
      else {digitalWrite(Bled, LOW);}
    if (Mbutton1 == 1) {digitalWrite(Wled, HIGH);}
      else {digitalWrite(Wled, LOW);}
    if (Hbutton1 == 1) {digitalWrite(Pled, HIGH);}
      else {digitalWrite(Pled, LOW);}
}

void loop() {
  while (WiFi.status() != WL_CONNECTED) { 
   digitalWrite(nterkirim, 0);
   WiFi.begin(ssid, password);
    delay(500);
    Serial.print(".");
  }
  sendsensor();
 }