
#include <HTTPClient.h>
#include <Wire.h>
#include "DHT.h" 
#include <WiFiClient.h>
#define  BLYNK_PRINT Serial
#include <BlynkSimpleEsp32.h>
#include "TRIGGER_WIFI_ESP32.h"               
#include "TRIGGER_GOOGLESHEETS_ESP32.h" 
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,20,4);

#define RL 10 //nilai RL =10 pada sensor
#define m -0.417 //hasil perhitungan gradien
#define b 0.825 //hasil perhitungan perpotongan
#define Ro 3   //hasil pengukuran RO
#define MQ A0 //definisi variabel A0
#define relay1 5 // cek kipas D5
#define relay2 18 // cek pompa air D18
#define relay3 19 // cek lampu D19
#define DHTPIN 15 // cek dht D15
#define LEDLAMPU 27
#define LEDNH3BERBAHAYA 26
#define LEDNH3TIDAKBERBAHAYA 25
#define DHTTYPE DHT11 //cek
int ENA = 14; // cek kecepatan motor D14
int IN1 = 12; // cek motor D12
int IN2 = 13; // cek motor D13
#define BLYNK_TEMPLATE_ID "TMPLtH-3qwTS"
#define BLYNK_DEVICE_NAME "Kandang Pintar"
#define BLYNK_AUTH_TOKEN "NT6eXsYl-Y9WTjYbx1X-1IbfDpKw6Hhz"

String server = "http://maker.ifttt.com";
String eventName = "Kandang_Pintar";
String IFTTT_Key = "mawkvey7ec7EirKWA7YmDwRdA1a9tz7t52PEM1jnkyi";
String IFTTTUrl="https://maker.ifttt.com/trigger/Kandang_Pintar/with/key/mawkvey7ec7EirKWA7YmDwRdA1a9tz7t52PEM1jnkyi";

const int numReadings = 5;//nilai penambilan sample pembacaan sebesar 5 kali
float readings[numReadings];      
int readIndex = 0;              
float total = 0;                  
float average = 0; 
DHT dht(DHTPIN, DHTTYPE); 
float value1;
float value2;
float value3;


const byte KARAKTER_DERAJAT = 0;
byte derajat[] = {
  B00111,
  B00101,
  B00111,
  B00000,
  B00000,
  B00000,
  B00000,
  B00000
};     

 char auth[] = BLYNK_AUTH_TOKEN;
 char ssid[] ="Prtttttt";
 char pass[] ="bismillah";
 WidgetLCD Lcd(V0);
 WidgetLED ledkipas(V4);
 WidgetLED ledpembersihanKotoran(V5);
 WidgetLED ledlampu(V6);


int sensorThres = 20;


BlynkTimer timer;

void sendSensor(){
 
 
  if(average> 20){
    Blynk.email("vedyhardino2@gmail.com", "Alert", "GAS BERBAHAYA!");
    Blynk.logEvent("nh3_alert","GAS BERBAHAYA");
  }
}

void setup() {
  Serial.begin(115200);
  dht.begin();
  lcd.init();
  lcd.createChar(KARAKTER_DERAJAT, derajat);
  lcd.backlight();
  Blynk.begin(auth, ssid, pass, "blynk.cloud",80 );
  timer.setInterval(2500L, sendSensor);
  pinMode(MQ,INPUT); // cek
  pinMode(relay1,OUTPUT); // cek kipas 
  pinMode(relay2,OUTPUT); // cek pompa air
  pinMode(relay3,OUTPUT); // cek lampu
  pinMode(ENA, OUTPUT); // cek
  pinMode(IN1, OUTPUT); // cek
  pinMode(IN2, OUTPUT); // cek
  pinMode(LEDLAMPU, OUTPUT); // cek
  pinMode(LEDNH3BERBAHAYA, OUTPUT); // cek
  pinMode(LEDNH3TIDAKBERBAHAYA, OUTPUT); // cek
  digitalWrite(IN1, LOW); // cek
  digitalWrite(IN2, LOW); // cek
  digitalWrite (relay1,1); //cek
  digitalWrite (relay2,1); //cek
  digitalWrite (relay3,0); //cek
   for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
for (int times = 1; times <=5; times++) {
    lcd.setCursor(0,0);
    lcd.print("  pre heating");
    lcd.setCursor(3,1);
    lcd.print(times);
    lcd.print(" seconds");
    delay(1000);
  }
  lcd.clear();
}


void sendDataToSheet(void)
{
  String url = server + "/trigger/" + eventName + "/with/key/" + IFTTT_Key + "?value1=" + String((float)value1) + "&value2="+String((float)value2) +"&value3=" + String((float)value3);  
  Serial.println(url);
  //Start to send data to IFTTT
  HTTPClient http;
  Serial.print("[HTTP] begin...\n");
  http.begin(url); //HTTP

  Serial.print("[HTTP] GET...\n");
  // start connection and send HTTP header
  int httpCode = http.GET();
  // httpCode will be negative on error
  if(httpCode > 0) {
    // HTTP header has been send and Server response header has been handled
    Serial.printf("[HTTP] GET... code: %d\n", httpCode);
    // file found at server
    if(httpCode == HTTP_CODE_OK) {
      String payload = http.getString();
      Serial.println(payload);
    }
  } else {
    Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
  }
  http.end();

}

void loop() {
Blynk.run();
  timer.run();
  float Hum = dht.readHumidity();
  value1 = Hum ;
  float Temp = dht.readTemperature();
  value2 = Temp;
  float VRL; 
  float RS;  
  float ratio; 
   
  VRL = analogRead(MQ)*(5/1023.0); //konversi analog ke tegangan
  RS =(5.0 /VRL-1)*10 ;//rumus untuk RS
  ratio = RS/Ro;  // rumus mencari ratio
  float ppm = pow(10, ((log10(ratio)-b)/m));//rumus mencari ppm
  
  total = total - readings[readIndex];
  readings[readIndex] = ppm;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }
  average = total / numReadings;
  value3 = average; 
  
 lcd.clear();
 lcd.setCursor(1,0);
 lcd.print("|");
 lcd.setCursor(3,0);
 lcd.print("KANDANG PINTAR"); 
 lcd.setCursor(18,0);
 lcd.print("|");
    
 lcd.setCursor(0,1);
 lcd.print("NH3 Amonia:");
 lcd.setCursor(12,1);
 lcd.print(average);
 delay(50);
 lcd.print("PPM");
 
 lcd.setCursor(0,2);
 lcd.print("Temperature:");
 lcd.setCursor(0,3);
 lcd.print("Humidity:");

 lcd.setCursor(13,2);
 lcd.print(Temp);
 delay(50);
 lcd.write(KARAKTER_DERAJAT);
  if(Temp < 10){
   lcd.setCursor(16, 2);
    }
  else{
    lcd.setCursor(19, 2);
   }
    lcd.print("C");

    lcd.setCursor(10, 3);
    lcd.print(Hum);
    delay(50);
    lcd.print(" %");



if (Temp >=31){
    ledlampu.off();
    digitalWrite(LEDLAMPU, LOW);
    digitalWrite(relay3,1);
    }
 else {
    ledlampu.on();
    digitalWrite(LEDLAMPU, HIGH);
    digitalWrite(relay3,0);
    }

  
 if (average >=20){
    ledkipas.on();
    digitalWrite(LEDNH3BERBAHAYA, HIGH);
    digitalWrite(LEDNH3TIDAKBERBAHAYA, LOW);
    digitalWrite(relay1,0);
    }
 else  {
    ledkipas.off();
    digitalWrite(LEDNH3BERBAHAYA, LOW);
    digitalWrite(LEDNH3TIDAKBERBAHAYA, HIGH);
    digitalWrite(relay1,1);
   }

   
 if (average >=30){
    ledpembersihanKotoran.on();
    digitalWrite(relay2,0);
    digitalWrite(LEDNH3BERBAHAYA, HIGH);
    digitalWrite(LEDNH3TIDAKBERBAHAYA, LOW);
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, HIGH);
    analogWrite(ENA, 200);
    delay(5000);
  
    digitalWrite(IN1, HIGH);
    digitalWrite(IN2, LOW);
    analogWrite(ENA, 200);
    delay(2000);
    }
 else {
    ledpembersihanKotoran.off();
   // digitalWrite(LEDNH3BERBAHAYA, LOW);
   // digitalWrite(LEDNH3TIDAKBERBAHAYA, HIGH);
    digitalWrite(IN1, LOW);
    digitalWrite(IN2, LOW);
    digitalWrite(relay2,1);
    }

  Blynk.virtualWrite(V0,Temp);
  Blynk.virtualWrite(V1,Temp);  
  Lcd.print (1,0,"| MONITORING |");
  Lcd.print (1,1,"KANDANG PINTAR");
  Blynk.virtualWrite(V0,Hum);
  Blynk.virtualWrite(V2,Hum);
  Blynk.virtualWrite(V0,average);
  Blynk.virtualWrite(V3,average);
  delay (100) ;
  
  Serial.print("Values are ");
  Serial.print(value1);
  Serial.print(' ');
  Serial.print(value2);
  Serial.print(' ');
  Serial.println(value3);
  Serial.print(' '); 

  sendDataToSheet();
  delay(1000);
}
