#include <MQUnifiedsensor.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define         Board                   ("ESP-32")   
#define         Type                    ("MQ-2") 
#define         Voltage_Resolution      (3.3) 
#define         ADC_Bit_Resolution      (12) 
#define         RatioMQ2CleanAir        (60) 
#define         Pin                     (34)
#define         Flame_Sensor            (12)
#define         Buzzer                  (15)
MQUnifiedsensor MQ2(Board, Voltage_Resolution, ADC_Bit_Resolution, Pin, Type);
int buzzer = 13;
const char* ssid = "Wokwi-GUEST";
const char* password = "";
String server = "https://api.thingspeak.com/update?api_key=";
String fieldGasPpmStatus = "&field1=";
String fieldFireStatus = "&field2=";
String fieldEmergencyStatus = "&field3=";
String apiKey = "NYEEOVT55P3E5G5O";
boolean emergencyStatus;
HTTPClient http;
void setup() {
  Serial.begin(9600); 
  pinMode(Flame_Sensor, INPUT);
  pinMode(buzzer, OUTPUT);
  MQ2.setRegressionMethod(1); 
  MQ2.setA(44771); MQ2.setB(-3.245); 

  /*
    Exponential regression:
  Gas    | a      | b
  LPG    | 44771  | -3.245
  CH4    | 2*10^31| 19.01
  CO     | 521853 | -3.821
  Alcohol| 0.3934 | -1.504
  Benzene| 4.8387 | -2.68
  Hexane | 7585.3 | -2.849
  */

  MQ2.init(); 
  Serial.print("Calibrating please wait.");
  float calcR0 = 0;
  for(int i = 1; i<=10; i ++)
  {
    MQ2.update(); 
    calcR0 += MQ2.calibrate(RatioMQ2CleanAir);
    Serial.print(".");
  }
  MQ2.setR0(calcR0/10);
  Serial.println("  done!.");
  MQ2.serialDebug(true);


    WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println("Connecting to WiFi...");
    delay(500);
  }
  digitalWrite(12, HIGH);
  emergencyStatus = false;
}

void loop() {
  MQ2.update();  
  float ppm = MQ2.readSensor();
  boolean isFireOn = digitalRead(Flame_Sensor);
  if(isFireOn==1 || ppm>=1000){
    emergencyStatus = true;
    tone(buzzer, 500); 
    delay(50);
    tone(buzzer, 700);
    delay(50);
  }
  else{
    emergencyStatus=false;
    tone(buzzer, 0);
  }
  Serial.print("PPM :");
  Serial.print(ppm);
  Serial.print("  ");
  Serial.print("Is Fire ON :");
  Serial.print(isFireOn);
  Serial.println("");
  String url = server+apiKey+fieldGasPpmStatus+String(ppm)+fieldFireStatus+String(isFireOn)+fieldEmergencyStatus+String(emergencyStatus);
  Serial.println(url);

  // Serial.println(url);
  if(WiFi.status() == WL_CONNECTED){
    Serial.println("Start update data to thingspeak");
    http.begin(url); 
    int httpCode = http.GET();
    if (httpCode > 0) {
      String payload = http.getString();
      Serial.println("HTTP GET request successful");
      Serial.println("Response:");
      Serial.println(payload);
  } else {
    Serial.println("Unexpected error");
  }
  http.end();
  }
 
  delay(15000);
}