#include <esp_task_wdt.h>

#define D2 2
#define D3 3
#define D4 4
#define D5 5
#define D6 6
#define A0_PIN 33
#define D10 10
#define D11 11
#define D12 12
#define ONBOARD_LED 15

int potValue = 0;
int timerDuration = 0;
unsigned long previousMillis = 0;
const long debounceDelay = 50;

void setup() {
  Serial.begin(115200);
  pinMode(D2, INPUT_PULLUP);
  pinMode(D3, INPUT_PULLUP);
  pinMode(D4, INPUT_PULLUP);
  pinMode(D5, INPUT_PULLUP);
  pinMode(D6, INPUT_PULLUP);
  pinMode(A0_PIN, INPUT);
  pinMode(D10, OUTPUT);
  pinMode(D11, OUTPUT);
  pinMode(D12, OUTPUT);
  pinMode(ONBOARD_LED, OUTPUT);
  
  digitalWrite(D10, LOW);
  digitalWrite(D11, LOW);
  digitalWrite(D12, LOW);

  esp_task_wdt_init(10, true); // Initialize watchdog with a timeout of 10 seconds, panic if triggered

  Serial.println("Setup completed.");
}

void loop() {
  esp_task_wdt_reset(); // Reset the watchdog timer

  int d2State = digitalRead(D2);
  int d3State = digitalRead(D3);
  int d4State = digitalRead(D4);
  int d5State = digitalRead(D5);
  int d6State = digitalRead(D6);

  // Blink onboard LED at 1Hz
  digitalWrite(ONBOARD_LED, HIGH);
  delay(500);
  digitalWrite(ONBOARD_LED, LOW);
  delay(2000);

  Serial.print("D2 State: ");
  Serial.println(d2State);
  Serial.print("D3 State: ");
  Serial.println(d3State);
  Serial.print("D4 State: ");
  Serial.println(d4State);
  Serial.print("D5 State: ");
  Serial.println(d5State);
  Serial.print("D6 State: ");
  Serial.println(d6State);
  
  // Washer
  if (d2State == LOW && d6State == LOW) {
    digitalWrite(D12, HIGH);
    while (digitalRead(D6) == LOW) {
      digitalWrite(D10, HIGH);
      delay(15000); // 15 seconds
      digitalWrite(D10, LOW);
    }
    digitalWrite(D12, LOW);
  }
  // Off
  else if (d2State == LOW) {
    digitalWrite(D10, LOW);
    digitalWrite(D11, LOW);
  }
  // Pulse
  else if (d3State == LOW) {
    digitalWrite(D10, HIGH);
    delay(500); // 0.5 seconds
    digitalWrite(D10, LOW);
    timerDuration = map(analogRead(A0_PIN), 0, 4095, 5000, 50000); // Mapping analog input to timer duration (5-50 seconds)
    delay(timerDuration);
  }
  // Low
  else if (d4State == LOW) {
    digitalWrite(D10, HIGH);
  }
  // High
  else if (d5State == LOW) {
    digitalWrite(D10, HIGH);
    digitalWrite(D11, HIGH);
  }
  else {
    digitalWrite(D12, LOW); // Ensure D12 is low if none of the conditions are met
  }
  
  delay(10); // Small delay to debounce
}
