#include <WiFi.h>
WiFiServer server(80);
String header;
unsigned long currentTime = millis();
unsigned long previousTime = 0;
const long timeoutTime = 2000;
String outputState;
void setup()
{
pinMode(2, OUTPUT);
Serial.begin(9600);
WiFi.begin("soc2019","socka2019");
while(WiFi.status() != WL_CONNECTED)
{
delay(250);
Serial.print(".");
}
Serial.println("WiFi uspesne pripojena!");
Serial.print("IP adresa: ");
Serial.println(WiFi.localIP());
server.begin();
}
void loop()
{
WiFiClient client = server.available(); // aktualizovanie prijatych dat
if (client) // ak sa pripojil klient
{
currentTime = millis();
previousTime = currentTime;
Serial.println("Novy klient");
String currentLine = ""; // premenna pre prijate data
while (client.connected() && currentTime - previousTime <= timeoutTime)
{
currentTime = millis();
if (client.available()) // test ci su prijate dake data
{
char c = client.read(); // nacitanie bajtu z buffera
Serial.write(c);
header += c;
if (c == '\n') // po ENTER je request
{
if (currentLine.length() == 0) // ak sa nacital prazdny riadok, odosli potvrdenie o spojeni
{
client.println("HTTP/1.1 200 OK");
client.println("Content-type:text/html");
client.println("Connection: close");
client.println("");
if (header.indexOf("GET /2/on") >= 0)
{
Serial.println("LED 2 on");
outputState = "on";
digitalWrite(2, HIGH);
}
else if (header.indexOf("GET /2/off") >= 0)
{
Serial.println("LED 2 off");
outputState = "off";
digitalWrite(2, LOW);
}
client.println("<!DOCTYPE html>");
client.println("<html>");
client.println("<head><style> p {color: blue;} h1 {color</style></head>");
client.println("<body><h1>ESP32 <a href=\"https://www.spsknm.sk/ssknm/\">web</a> server</h1>");
client.println("<p>LED " + outputState + "</p>");
if (outputState == "off")
client.println("<p><a href=\"/2/on\"><button class=\"button\">ON</button></a></p>");
else
client.println("<p><a href=\"/2/off\"><button class=\"button button2\">OFF</button></a></p>");
client.println("</body></html>");
client.println();
break;
}
else
{
currentLine = "";
}
}
else if (c != '\r')
{
currentLine += c; // add it to the end of the currentLine
}
}
}
header = "";
client.stop();
Serial.println("Klient je odpojeny.");
Serial.println("");
}
}