/* BLYNK CONNECTION INSTRUCTION
  V0:NAME
  V1:LATITUDE
  V2:MAP LONGITUDE
  EMAIL:[email protected]
  PASSWORD:zulora@2024
*/

#define led3       23
#define led2       18
#define buzzer     19

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

LiquidCrystal_I2C lcd(0x27,20,4);

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverUrl = "https://ny3.blynk.cloud/external/api/getAll?token=NozLO4x_WLpskXaPG50q15Gj-u8NTj5P";

String payload;
String v0,v1,v2;
String name;
String latitude;
String longitude;

void setup()
{
  lcd.init();                  
  lcd.backlight();
  loadingdisplay();
  
  Serial.begin(115200);
 
  pinMode(led3,OUTPUT);
  pinMode(led2,OUTPUT);
  pinMode(4, INPUT_PULLUP);
  pinMode(buzzer,OUTPUT);
  digitalWrite(buzzer,LOW);
  connectWify();
  digitalWrite(led3,HIGH);
  digitalWrite(led2,LOW);
  lcd.clear();
}


void loop()
{
  homedisplay();
  digitalWrite(led2,LOW);
  if (WiFi.status() == WL_CONNECTED) 
  {
    bool result = httpRead();
    if(result)
    {
      bool result2 = extractAndStore(payload);
      if(result2)
      {
        bool result3 = compareData();
        while(result3)
        {
          eventDisplay();
          Alert(1);
          digitalWrite(led2,HIGH);
          if(digitalRead(4)==LOW)
          {
            result3=LOW;
            lcd.clear();
          } 
        }
      }
    }
  }
  else
  {
    reconnectDisplay();
    connectWify();
    lcd.clear();
  }
}

bool compareData()
{
  bool state=LOW;
  if(name != v0)
  {
    name=v0;
    state=HIGH;
  }
  if(latitude != v1)
  {
    latitude=v1;
    state=HIGH;
  }
  if(longitude != v2)
  {
    longitude=v2;
    state=HIGH;
  }
  return state;
}

bool httpRead()
{
  HTTPClient http;
  http.begin(serverUrl);
  int httpResponseCode = http.GET();
  if (httpResponseCode > 0) 
  {
    payload = http.getString();
    Serial.println("HTTP Response code: " + String(httpResponseCode));
    Serial.println("Response data: " + payload);
    http.end();
    return HIGH;
  } 
  else 
  {
    Serial.println("Error on HTTP request");
    http.end();
    return LOW;
  }
}

void connectWify()
{
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) 
  {
    delay(1000);
    Serial.println("Connecting to WiFi...");
  }
  Serial.println("Connected to WiFi");
}

void loadingdisplay()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("*  LORA BASED FIRE  *"); 
  lcd.setCursor(0,1);
  lcd.print("*  ALERT SYSTEM    *"); 
  lcd.setCursor(0,2);
  lcd.print(" SYSTEM INITIALIZE ");
  lcd.setCursor(0,3);
  lcd.print("PLEASE WAIT");
  for(int k=11;k<20;k++)
  {
    lcd.setCursor(k,3);
    lcd.print(".");
    delay(500);
  }
}

void homedisplay()
{
  lcd.setCursor(0,0);
  lcd.print("********************"); 
  lcd.setCursor(0,1);
  lcd.print("* NO FIRE ACCIDENT *");
  lcd.setCursor(0,2);
  lcd.print("*     REPORTED     *");
  lcd.setCursor(0,3);
  lcd.print("********************");  
  delay(500);
}

void reconnectDisplay()
{
  lcd.setCursor(0,0);
  lcd.print("*******!ERROR!******"); 
  lcd.setCursor(0,1);
  lcd.print("* NO WiFY NETWORK  *");
  lcd.setCursor(0,2);
  lcd.print("*  RECONECTING...  *");
  lcd.setCursor(0,3);
  lcd.print("********************");  
  delay(500);
}

void eventDisplay()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("FIRE DETECTED AT:"); 
  lcd.setCursor(0,1);
  lcd.print(name); 
  lcd.setCursor(0,2);
  lcd.print("LATITUDE:"); 
  lcd.setCursor(10,2);
  lcd.print(latitude); 
  lcd.setCursor(0,3);
  lcd.print("LONGITUDE:"); 
  lcd.setCursor(10,3);
  lcd.print(longitude); 
}

void Alert(uint8_t num)
{
  for(num;num>0;num--)
  {
    digitalWrite(buzzer,HIGH);
    delay(750);
    digitalWrite(buzzer,LOW);
    delay(500);
  }
}

bool extractAndStore(String jsonString) 
{
  StaticJsonDocument<200> doc;  // Allocate a buffer for parsing the JSON data
  DeserializationError error = deserializeJson(doc, jsonString);  // Deserialize the JSON data
  if (error)  // Check for errors
  {
    Serial.print("Failed to parse JSON: ");
    Serial.println(error.c_str());
    return LOW;
  }
  String data0 = doc["v0"];   
  v0=data0;
  String data1 = doc["v1"];
  v1=data1;
  String data2 = doc["v2"];
  v2=data2;
  Serial.println("Extracted Values:");  // Print extracted values for verification
  Serial.print("v0: ");
  Serial.println(v0);
  Serial.print("v1: ");
  Serial.println(v1);
  Serial.print("v2: ");
  Serial.println(v2);
  return HIGH;
}