#define BLYNK_TEMPLATE_ID "TMPL2FauFfWeh"
#define BLYNK_TEMPLATE_NAME "PARTIENT MONITORING VIA IOT"
#define BLYNK_AUTH_TOKEN "O4xsE5TU6L1uL_1boOmcNYi7ySVxqO9b"

//BASIC CONNECTIONS
#define GLED 4
#define RLED 5
#define SPIN 32
#define TPIN 33
#define HPIN 35

#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <LiquidCrystal_I2C.h>
LiquidCrystal_I2C lcd(0x27,16,2);

char auth[] = BLYNK_AUTH_TOKEN;
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

float Temperature;
float bpm;
float spo2;
String notification;
String code;
bool dstate;

void setup()
{
  lcd.init();                  
  lcd.backlight();
  loadingdisplay();
  Serial.begin(115200);
  pinMode(GLED,OUTPUT);
  pinMode(RLED,OUTPUT);
  digitalWrite(GLED,LOW);
  digitalWrite(RLED,HIGH);
  Blynk.begin(auth, ssid, pass);
  digitalWrite(GLED,HIGH);
  digitalWrite(RLED,HIGH);
}

void loop()
{
  homedisplay();
 Blynk.run();
 get_Temp();
 get_bpm();
 get_spo2();
 checkAbnormal();
 send_update();
}

void loadingdisplay()
{
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("PATIENT MONITOR"); 
  lcd.setCursor(0,1);
  lcd.print("SYSTEM VIA IOT"); 
  delay(2000);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("DEVICE BOOTING");
  lcd.setCursor(0,1);
  lcd.print("WAIT");
  for(int k=4;k<16;k++)
  {
    lcd.setCursor(k,3);
    lcd.print(".");
    delay(500);
  }
}

void homedisplay()
{
  lcd.setCursor(0,0);
  if(dstate)
  {
    lcd.print("DEVICE CONNECTED");
  }
  else
  {
    lcd.print("  DISCONNECTED  ");
  }
  lcd.setCursor(0,1);
  lcd.print("****************");
  delay(500);
}


void checkAbnormal()
{
  if(Temperature>40)
  {
     code="01TEHI";
  }
  else if(Temperature<25)
  {
     code="01TELO";
  }
  else if(bpm>120)
  {
     code="01HRHI";
  }
  else if(bpm<80)
  {
     code="01HRLO";
  }

  else if(spo2>95)
  {
     code="01TEHI";
  }
  else if(spo2<90)
  {
     code="01TELO";
  }
  else
  {
      code = "NORMAL";
  }
  Serial.print("CODE IS :");
  Serial.println(code);
}

void get_Temp()
{       
  int signal1 = analogRead(TPIN);  
  Temperature= map(signal1,0,4095,20,50);
  Serial.print("TEMPERATURE IS :");
  Serial.println(Temperature);
}

void get_bpm() 
{
  int signal2 = analogRead(HPIN); 
  bpm= map(signal2,0,4095,50,150);
  Serial.print("HEATRATE IS :");
  Serial.println(bpm);
}

void get_spo2() 
{
  int signal3 = analogRead(SPIN); 
  spo2= map(signal3,0,4095,50,120);
  Serial.print("SPO2 IS :");
  Serial.println(spo2);
}

void send_update() 
{
  Blynk.virtualWrite(V0,bpm);
  Blynk.virtualWrite(V1,Temperature);
  Blynk.virtualWrite(V2,spo2);
  Blynk.virtualWrite(V3,notification);
  Blynk.virtualWrite(V4,code);
  delay(500);  
}