#include <ESP32Servo.h>
#define BLYNK_PRINT Serial
#include <WiFi.h>
#include <WiFiClient.h>
#include <BlynkSimpleEsp32.h>

#define SSID "Wokwi-GUEST"
#define PASSWORD ""

#define BLYNK_TEMPLATE_ID "TMPLObU70-yy"
#define BLYNK_DEVICE_NAME "Automatic Feeding"
#define BLYNK_AUTH_TOKEN "gWdV2E3YIgSyB0r7OpXY6cXUiA9-QGIQ"

int LED_Pump = 15; // กำหนดขา Pin LED 

Servo myservo;

typedef enum
{
  PUMP_NONE =0,  //ไม่มีคำสั่ง
  PUMP_ON,    //คำสั่งเปิดมอเตอร์
  PUMP_OFF,   //คำสั่งปิดมอเตอร์
}PUMP_en;

PUMP_en pump;

BLYNK_WRITE(V4)
{
  if(param.asInt()) 
  {
    Serial.println("Pump on recv");
    pump = PUMP_ON;
  }
  else
  {
    Serial.println("Pump off recv");
    pump = PUMP_OFF;
  }
}

void PumpSwitchON()
{
  Blynk.virtualWrite(V0, 1);
  digitalWrite(LED_Pump,HIGH);
  myservo.write(0);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}

void PumpSwitchOFF()
{
  Blynk.virtualWrite(V0, 0);
  digitalWrite(LED_Pump,LOW);
  myservo.write(90);                  // sets the servo position according to the scaled value
  delay(15);                           // waits for the servo to get there
}

void setup() 
{
  
  Serial.begin(9600); // ความเร็ว Serial Port 9600

  Serial.println("Start your Engine");
  
  pinMode(LED_Pump, OUTPUT);

  WiFi.begin(SSID, PASSWORD); // WiFi เริ่มทำงาน
  Serial.printf("WiFi connecting to %s\n",  SSID);
  while (WiFi.status() != WL_CONNECTED) // check การเชื่อมต่อ WiFi วนลูปจนกว่าจะต่อ WiFi ได้
  {
    Serial.print(".");
    delay(400);
  }
  Serial.printf("\nWiFi connected\nIP : ");
  Serial.println(WiFi.localIP()); // แสดงค่า IP Address ที่ต่อ WiFi ได้ ออกทาง Serial Port

  Blynk.begin(BLYNK_AUTH_TOKEN, SSID, PASSWORD, "blynk.cloud", 80); //เชื่อมต่อ Blynk Server
  
  myservo.attach(25);
}
void loop()
{
  Blynk.run(); // รัน blynk
  delay(100);

  switch(pump) 
  {
    case PUMP_NONE: PumpSwitchOFF(); break;
    case PUMP_ON:   PumpSwitchON(); break;
    case PUMP_OFF:  PumpSwitchOFF(); break;
  }

}