///Template ID,Device Name,Auth Token จาก device info ใน blynk clound
#define BLYNK_TEMPLATE_ID "TMPL6son8YSBw"
#define BLYNK_TEMPLATE_NAME "Quickstart Template"
#define BLYNK_AUTH_TOKEN "f2YBMbepMTGlxiCfw0TTaqLfTkIXRT5O"


#define BLYNK_PRINT Serial


#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>
#include <DHT.h>
#define DHTPIN 5
#define DHTTYPE  DHT22
DHT dht(DHTPIN, DHTTYPE);

///wifi id & pwd
char ssid[] = "Wokwi-GUEST";
char pass[] = "";

BlynkTimer timer;

// This function is called every time the Virtual Pin 0 state changes
BLYNK_WRITE(V0)
{
  // Set incoming value from pin V0 to a variable
  int value = param.asInt();
  Serial.println(value);
  if(value >= 1){
    digitalWrite(4, LOW);
  }else {
    digitalWrite(4, HIGH);
  }
  // Update state
  Blynk.virtualWrite(V1, value);
}
BLYNK_WRITE(V4)
{
  // Set incoming value from pin V0 to a variable
  int value = param.asInt();
  Serial.println(value);
  if(value >= 1){
    digitalWrite(4, LOW);
  }else {
    digitalWrite(4, HIGH);
  }
  // Update state
  Blynk.virtualWrite(V1, value);
}

// This function is called every time the device is connected to the Blynk.Cloud
BLYNK_CONNECTED()
{
  // Change Web Link Button message to "Congratulations!"
  Blynk.setProperty(V3, "offImageUrl", "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations.png");
  Blynk.setProperty(V3, "onImageUrl",  "https://static-image.nyc3.cdn.digitaloceanspaces.com/general/fte/congratulations_pressed.png");
  Blynk.setProperty(V3, "url", "https://docs.blynk.io/en/getting-started/what-do-i-need-to-blynk/how-quickstart-device-was-made");
}

// This function sends Arduino's uptime every second to Virtual Pin 2.
void checktemp()
{
  float t = dht.readTemperature();
 if (isnan(t)) {
    Serial.println("Failed to read from DHT sensor!");
    return;
 }
  Blynk.virtualWrite(V2, t);
}

void setup()
{
  // Debug console
  Serial.begin(115200);
  dht.begin();
  Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass);
  // You can also specify server:
  //Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, "blynk.cloud", 80);
  //Blynk.begin(BLYNK_AUTH_TOKEN, ssid, pass, IPAddress(192,168,1,100), 8080);

  // Setup a function to be called every second
  timer.setInterval(1000L, checktemp);
  pinMode(4, OUTPUT);
  digitalWrite(4, HIGH);

}

void loop()
{
  Blynk.run();
  timer.run();
  // You can inject your own code or combine it with other sketches.
  // Check other examples on how to communicate with Blynk. Remember
  // to avoid delay() function!
}