#include <WiFi.h>
#include <HTTPClient.h>

// Replace with your network credentials
const char* ssid = "wokwi-GUEST";
const char* password = "";

// Replace with your Telegram BOT token and chat ID
String botToken = "7319685759:AAHkgvBD73CpMeUEe_rvowZMSLLgmDx6m3g";
String chatID = "1623780474";

// Gas sensor pins
const int analogPin = 22; // AO pin of the gas sensor
const int digitalPin = 23; // DO pin of the gas sensor

// LED pins
const int redPin = 18; // Red LED pin
const int greenPin = 19; // Green LED pin

void setup() {
  Serial.begin(115200); // Starting Serial Terminal
  
  pinMode(analogPin, INPUT);
  pinMode(digitalPin, INPUT);
  
  pinMode(redPin, OUTPUT);
  pinMode(greenPin, OUTPUT);

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loop() {
  // Read the analog and digital values from the gas sensor
  int analogValue = analogRead(analogPin);
  int digitalValue = digitalRead(digitalPin);

  // Print the sensor values to the Serial Monitor
  Serial.print("Analog Value: ");
  Serial.println(analogValue);
  Serial.print("Digital Value: ");
  Serial.println(digitalValue);

  // Control the LEDs based on the digital output of the gas sensor
  if (digitalValue == HIGH) {
    digitalWrite(redPin, HIGH); // Turn on red LED
    digitalWrite(greenPin, LOW); // Turn off green LED
  } else {
    digitalWrite(redPin, LOW); // Turn off red LED
    digitalWrite(greenPin, HIGH); // Turn on green LED
  }

  // Send a notification to Telegram if the gas concentration is above a threshold
  if (digitalValue == HIGH) { // Change the threshold as needed
    sendTelegramMessage("Gas concentration is above threshold. Analog Value: " + String(analogValue));
  }

  delay(1000);
}

void sendTelegramMessage(String message) {
  if (WiFi.status() == WL_CONNECTED) {
    HTTPClient http;
    String url = "https://api.telegram.org/bot" + botToken + "/sendMessage?chat_id=" + chatID + "&text=" + message;
    Serial.println("Sending message to Telegram: " + message);
    http.begin(url);
    int httpResponseCode = http.GET();
    if (httpResponseCode > 0) {
      String response = http.getString();
      Serial.println(httpResponseCode);
      Serial.println(response);
    } else {
      Serial.print("Error on sending GET: ");
      Serial.println(httpResponseCode);
    }
    http.end();
  } else {
    Serial.println("WiFi Disconnected");
  }
}