/*
*on/off LED mounted
*on board
*communication acted
*using AJAX
*esp8266_nodemcu_ajax_onoff.ino
*/
#include <ESP8266WiFi.h> #include <WiFiClient.h> #include <ESP8266WebServer.h> #include<ESP8266mDNS.h>

#include "index.h" //Web page header file
#define LED LED_BUILTIN

const char* ssid = "FASTWEB_fabio";
const char* password = "fabionetwifi";

ESP8266WebServer server(80);

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void handleRoot() {
String s = MAIN_page; //Read HTML contents
server.send(200, "text/html", s); //Send web page
}

void handleLED() {
String ledState = "OFF";
String t_state = server.arg("LEDstate"); //Refer xhttp.open("GET", "setLED?LEDstate="+led, true);
Serial.println(t_state);
if(t_state == "1")
{
digitalWrite(LED,LOW); //LED ON
ledState = "ON"; //Feedback parameter
}
else
{
digitalWrite(LED,HIGH); //LED OFF
ledState = "OFF"; //Feedback parameter
}

server.send(200, "text/plane", ledState); //Send web page
}

//===============================================================
// Setup
//===============================================================

void setup(void){
Serial.begin(115200);
Serial.println("");
Serial.println("Booting Sketch...");
delay(1000);

WiFi.mode(WIFI_STA); //Connectto your wifi
WiFi.begin(ssid, password);

pinMode(LED,OUTPUT);

Serial.print("Connecting to... ");
Serial.print(ssid);

//Wait for WiFi to connect
while(WiFi.status() != WL_CONNECTED){
delay(500);
Serial.print(".");
}

//If connection successful show IP address in serial monitor
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP()); //IP address assigned to your ESP
//----------------------------------------------------------------

server.on("/", handleRoot); //This is display page
server.on("/setLED",handleLED);//To get update LED
server.begin(); //Start server
Serial.println("HTTP server started");
}

//===============================================================
// This routine is executed when you open its IP in browser
//===============================================================
void loop(void){
server.handleClient(); //handle client requests
}