/* BLYNK CONNECTION INSTRUCTION
  V0:flowrate01
  V1:flowrate02
  V2:flowrate03
  V3:notification
  v4:command  format ON:OFF
*/


#define BLYNK_PRINT Serial
#define BLYNK_TEMPLATE_ID "TMPL22b6hk3vu"
#define BLYNK_TEMPLATE_NAME "OXYGEN LEAKAGE"
#define BLYNK_AUTH_TOKEN "FIuylpJXpmt3Zfd6JG5uUctE8XXNKD6d"

#define bled       23
#define gled       18
#define buzzer     4

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

const char* ssid = "Wokwi-GUEST";
const char* password = "";
const char* serverUrl = "https://ny3.blynk.cloud/external/api/getAll?token=FIuylpJXpmt3Zfd6JG5uUctE8XXNKD6d";
const char* serverUrl1 = "https://ny3.blynk.cloud/external/api/update?token=FIuylpJXpmt3Zfd6JG5uUctE8XXNKD6d&v2=";
String payload;
String v0,v1,v2,v3,v4;

bool rState;

void setup()
{
  Serial.begin(115200);
 
  pinMode(gled,OUTPUT);
  pinMode(bled,OUTPUT);
  digitalWrite(gled,LOW);
  digitalWrite(bled,LOW);
  connectWify();
  digitalWrite(bled,HIGH);
  digitalWrite(gled,LOW);
}


void loop()
{
  if (WiFi.status() == WL_CONNECTED) 
  {
    httpWrite();
    bool result = httpRead();
    if(result)
    {
      bool result2 = extractAndStore(payload);
      if(result2)
      {
        if(v4=="OFF:OFF" || v4=="ON:OFF")
        {
          digitalWrite(gled,LOW);
          Alert(2);
        }
        if(v4=="ON:ON" || v4=="OFF:ON")
        {
          digitalWrite(gled,HIGH);
        }  
      }
    }
  }
  else
  {
    connectWify();
  }
}


bool httpWrite()
{
  int flowrate=map(analogRead(34),0,4092,0,100);
  HTTPClient http;
  http.begin(serverUrl1+String(flowrate));
  int httpResponseCode = http.GET();
  if (httpResponseCode > 0) 
  {
    payload = http.getString();
    Serial.println("HTTP Response code: " + String(httpResponseCode));
    Serial.println("Response data: " + payload);
    http.end();
    Serial.println("update done");
    return HIGH;
  } 
  else 
  {
    Serial.println("Error on HTTP request");
    http.end();
    return LOW;
  }
}

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 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;
  String data3 = doc["v3"];
  v3=data3;
  String data4 = doc["v4"];
  v4=data4;
  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);
  Serial.print("v3: ");
  Serial.println(v3);
  Serial.print("v4: ");
  Serial.println(v4);
  return HIGH;
}