#define BLYNK_TEMPLATE_ID "TMPL6yAzjdQoO"
#define BLYNK_TEMPLATE_NAME "GSM"
#define BLYNK_AUTH_TOKEN "A7dXsLLBa4N5NDpWis5EEvbvi4Sm83Gi"

/* Comment this out to disable prints and save space */
#define BLYNK_PRINT Serial

#define TINY_GSM_MODEM_SIM800

#include <TinyGsmClient.h>
#include <BlynkSimpleTinyGSM.h>

// GSM Modülü bağlantı ayarları
char apn[]  = "internet";
char user[] = "";
char pass[] = "";

#include <SoftwareSerial.h>
SoftwareSerial SerialAT(10, 11); // RX, TX
TinyGsm modem(SerialAT);

// Röle çıkış pinleri
#define RELAY_2 2
#define RELAY_3 3
#define RELAY_4 4
#define RELAY_5 5

void setup()
{
  // Debug console
  Serial.begin(9600);

  // GSM modülü başlatma
  SerialAT.begin(9600);
  delay(3000);
  Serial.println("Initializing modem...");
  modem.restart();

  Blynk.begin(BLYNK_AUTH_TOKEN, modem, apn, user, pass);

  // Röle pinlerini çıkış olarak ayarla
  pinMode(RELAY_2, OUTPUT);
  pinMode(RELAY_3, OUTPUT);
  pinMode(RELAY_4, OUTPUT);
  pinMode(RELAY_5, OUTPUT);

  // Röleleri başlangıçta kapalı (HIGH) duruma getir
  digitalWrite(RELAY_2, HIGH);
  digitalWrite(RELAY_3, HIGH);
  digitalWrite(RELAY_4, HIGH);
  digitalWrite(RELAY_5, HIGH);

  Serial.println("System initialized. All relays are OFF.");
}

void loop()
{
  Blynk.run();
}

// Virtual Pin V0'dan gelen komut RELAY_0'ı kontrol eder
BLYNK_WRITE(V0)
{
  int value = param.asInt();
  digitalWrite(RELAY_2, value == 1 ? LOW : HIGH); // Röleyi kontrol et
  Serial.print("RELAY_2: ");
  Serial.println(value == 1 ? "ON" : "OFF");
}

// Virtual Pin V1'den gelen komut RELAY_1'i kontrol eder
BLYNK_WRITE(V1)
{
  int value = param.asInt();
  digitalWrite(RELAY_3, value == 1 ? LOW : HIGH); // Röleyi kontrol et
  Serial.print("RELAY_3: ");
  Serial.println(value == 1 ? "ON" : "OFF");
}

// Virtual Pin V2'den gelen komut RELAY_2'yi kontrol eder
BLYNK_WRITE(V2)
{
  int value = param.asInt();
  digitalWrite(RELAY_4, value == 1 ? LOW : HIGH); // Röleyi kontrol et
  Serial.print("RELAY_4: ");
  Serial.println(value == 1 ? "ON" : "OFF");
}

// Virtual Pin V3'ten gelen komut RELAY_3'ü kontrol eder
BLYNK_WRITE(V3)
{
  int value = param.asInt();
  digitalWrite(RELAY_5, value == 1 ? LOW : HIGH); // Röleyi kontrol et
  Serial.print("RELAY_5: ");
  Serial.println(value == 1 ? "ON" : "OFF");
}