#include <WiFi.h>
#include <WebServer.h>
#include "webpage.h" // Include the HTML file
const char* ssid = "your_SSID"; // Replace with your WiFi SSID
const char* password = "your_PASSWORD"; // Replace with your WiFi Password
WebServer server(80);
// Relay pin
const int relayPin = 5;
unsigned long timerEndTime = 0;
bool timerActive = false;
void handleRoot() {
// Send the HTML page to the client
server.send_P(200, "text/html", MAIN_page);
}
void handleStartTimer() {
if (timerActive) {
server.send(200, "text/plain", "Timer already running.");
return; // Don't start a new timer if one is active
}
if (server.hasArg("duration")) {
int duration = server.arg("duration").toInt();
timerEndTime = millis() + (duration * 1000);
timerActive = true;
server.send(200, "text/plain", "Timer started");
} else {
server.send(400, "text/plain", "Invalid duration");
}
}
void handleStatus() {
unsigned long timeRemaining = 0;
if (timerActive) {
timeRemaining = (timerEndTime - millis()) / 1000;
if (millis() > timerEndTime) {
timerActive = false;
digitalWrite(relayPin, HIGH); // Turn on the relay when the timer ends
}
}
String json = "{\"timeRemaining\":\"";
if (timerActive) {
unsigned long minutes = timeRemaining / 60;
unsigned long seconds = timeRemaining % 60;
json += String(minutes) + ":" + (seconds < 10 ? "0" : "") + String(seconds);
} else {
json += "No timer is active.";
}
json += "\", \"relayState\":";
json += digitalRead(relayPin) == HIGH ? "true" : "false";
json += "}";
server.send(200, "application/json", json);
}
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
// Set up relay pin
pinMode(relayPin, OUTPUT);
digitalWrite(relayPin, LOW); // Ensure the relay is off at startup
// Connecting to WiFi
Serial.println("Connecting to WiFi...");
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.print(".");
}
Serial.println("\nConnected to WiFi!");
// Print the ESP32 IP address
Serial.print("ESP32 IP Address: ");
Serial.println(WiFi.localIP());
// Set up the server endpoints
server.on("/", handleRoot);
server.on("/start", handleStartTimer);
server.on("/status", handleStatus);
server.begin();
Serial.println("HTTP server started");
}
void loop() {
server.handleClient();
}