#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <uri/UriBraces.h>
#include <HTTPClient.h>
// WiFi config
#define WIFI_SSID "Wokwi-GUEST"
#define WIFI_PASSWORD ""
#define WIFI_CHANNEL 6
WebServer server(80);
// LED demo
const int LED1 = 26;
const int LED2 = 27;
// Sensore simulato cancello (pulsante)
const int GATE_SENSOR = 25;
bool led1State = false;
bool led2State = false;
bool lastGateState = LOW;
// debounce
unsigned long lastTrigger = 0;
const int debounceMs = 3000;
// 🔥 endpoint simulazione (NO AWS)
const char* lambdaUrl = "https://httpbin.org/post";
// ===================== HTML =====================
void sendHtml() {
String response = R"(
<!DOCTYPE html><html>
<head>
<title>ESP32 Web Server Demo</title>
</head>
<body>
<h1>ESP32 Web Server</h1>
<p>Premi il pulsante su pin 25 per simulare il cancello</p>
<a href="/toggle/1">Toggle LED1</a><br><br>
<a href="/toggle/2">Toggle LED2</a>
</body>
</html>
)";
server.send(200, "text/html", response);
}
// ===================== SIMULAZIONE LAMBDA =====================
void callLambda(const char* eventType) {
if (WiFi.status() == WL_CONNECTED) {
HTTPClient http;
http.begin(lambdaUrl); // ✔ ora client esiste
http.setTimeout(5000);
http.addHeader("Content-Type", "application/json");
String payload = String("{\"event\":\"") + eventType + "\"}";
int httpResponseCode = http.POST(payload);
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
if (httpResponseCode > 0) {
Serial.println(http.getString());
} else {
Serial.println(http.errorToString(httpResponseCode));
}
http.end();
}
}
// ===================== SETUP =====================
void setup(void) {
Serial.begin(115200);
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(GATE_SENSOR, INPUT_PULLUP);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD, WIFI_CHANNEL);
Serial.print("Connessione WiFi");
while (WiFi.status() != WL_CONNECTED) {
delay(100);
Serial.print(".");
}
Serial.println(" Connesso!");
Serial.print("IP: ");
Serial.println(WiFi.localIP());
server.on("/", sendHtml);
server.on(UriBraces("/toggle/{}"), []() {
String led = server.pathArg(0);
switch (led.toInt()) {
case 1:
led1State = !led1State;
digitalWrite(LED1, led1State);
break;
case 2:
led2State = !led2State;
digitalWrite(LED2, led2State);
break;
}
sendHtml();
});
server.begin();
Serial.println("HTTP server avviato");
}
// ===================== LOOP =====================
void loop(void) {
server.handleClient();
bool currentState = digitalRead(GATE_SENSOR);
// debug temporaneo — rimuovilo dopo
static unsigned long lastPrint = 0;
if (millis() - lastPrint > 1000) {
Serial.print("PIN 25: ");
Serial.println(currentState);
lastPrint = millis();
}
if (currentState == LOW && lastGateState == HIGH) {
if (millis() - lastTrigger > debounceMs) {
Serial.println("🚪 Cancello aperto!");
callLambda("gate_open");
lastTrigger = millis();
}
}
lastGateState = currentState;
delay(50);
}