Esp8266 is a chip that supports the tcp / ip protocol. With this chip for a few dollars you can log into the IOT world and create wonders. There are 2 ways to track or manipulate any data dynamically with the ESP8266. One is AJAX and the other is Websocket technology.

AJAX, in early 2000, made static websites dynamic. Asynchronous JavaScript and XML (AJAX) creates a bridge between the server and client and keeps it open. This structure makes static sites dynamic. This technique is called long probe. At the beginning of 2010, as data traffic increased, the connection between the server and the customer became longer and longer.

The following code is dynamically sending data with AJAX. ESP8266 is the server here. Once you have entered the IP address in the web browser, connect to the client when you are connected. In C ++, writing HTML as a string is really simple and very simple.

#include <ESP8266WiFi.h>

#include <ESP8266WebServer.h>



ESP8266WebServer server(80); // 80 is the port number



const char* ssid="Newton";

const char* password="X1t3q567ZO.#";



String Website,data,XML,Javascript;

int inc=0;



void javascriptContent(){

    Javascript ="<SCRIPT>\n";

    Javascript+="var xmlHttp=createXmlHttpObject();\n";

    Javascript+="function createXmlHttpObject(){\n";

    Javascript+="if(window.XMLHttpRequest){\n";

    Javascript+="xmlHttp=new XMLHttpRequest();\n";

    Javascript+="}else{\n";

    Javascript+="xmlHttp=new ActiveXObject(\'Microsoft.XMLHTTP\');\n";

    Javascript+="}\n";

    Javascript+="return xmlHttp;\n";

    Javascript+="}\n";

    Javascript+="\n";

    Javascript+="function response(){\n";

    Javascript+="xmlResponse=xmlHttp.responseXML;\n";

    Javascript+="xmldoc = xmlResponse.getElementsByTagName(\'data\');\n";

    Javascript+="message = xmldoc[0].firstChild.nodeValue;\n";

    Javascript+="document.getElementById(\'div1\').innerHTML=message;\n";

    Javascript+="}\n";



    Javascript+="function process(){\n";

    Javascript+="xmlHttp.open(\'PUT\',\'xml\',true);\n";

    Javascript+="xmlHttp.onreadystatechange=response;\n";

    Javascript+="xmlHttp.send(null);\n";

    Javascript+="setTimeout(\'process()\',200);\n";

    Javascript+="}\n";

    

    Javascript+="</SCRIPT>\n";

    

  

  }



void WebsiteContent(){

    javascriptContent();

    

    Website="<html>\n";

    Website+="<style>\n";

    Website+="#div1{\n";

    Website+="width:400px;\n";

    Website+="margin:0 auto;\n";

    Website+="margin-top:130px;\n";

    Website+="font-size:900%;\n";

    Website+="color:powderblue;\n";

    Website+="}\n";

    Website+="</style>\n";

    Website+="<body onload=\'process()\'>";

    Website+="<div id=\'div1\'>"+data+"</div></body></html>";

    Website+=Javascript;

    server.send(200,"text/html",Website);

  }

void XMLcontent(){



  XML ="<?xml version=\'1.0\'?>";

  XML+="<data>";

  XML+=data;

  XML+="</data>";



  server.send(200,"text/xml",XML);

  

  }



void setup() {

  // put your setup code here, to run once:

  Serial.begin(9600);

  WiFi.begin(ssid,password);

  while(WiFi.status()!=WL_CONNECTED)delay(500);

  WiFi.mode(WIFI_STA);

  Serial.print(WiFi.localIP());

  server.on("/",WebsiteContent);

  server.on("/xml",XMLcontent);

  server.begin();





}



void loop() {

  // put your main code here, to run repeatedly:

  inc = inc + 1;

  data=(String)inc;

  server.handleClient();



}

But there is something here that should not be forgotten. ESP8266 should send TCP packets in one step. ESP8266 packages not found. If you send a long packet, ESP should send it without looking at its length. If the size of the TCP packets is long, ESP8266 is killed. It can be reset. Instead of using html and css to fix this, design with Javascript as much as possible.

#include <ESP8266WiFi.h>

#include <ESP8266WebServer.h>



 

#define CS 15                   //define chip select line for manual control



ESP8266WebServer server(80);





const char* ssid="Newton"; 

const char* password="X1t3q567ZO.#"; 



String webSite,javaScript,XML;

int LED=5;

int start=0;



void buildWebsite(){

  buildJavascript();

  webSite="<!DOCTYPE HTML>\n";

  webSite+=javaScript;

  webSite+="<HTML>\n";

  webSite+="<style>\n";

  webSite+="#button {\n";

  webSite+="background-color: #E6E6FA;\n";

  webSite+="border: none;\n";

  webSite+="color: white;\n";

  webSite+="padding: 32px;\n";

  webSite+=" text-align: center;\n";

  webSite+=" text-decoration: none;\n";

  webSite+="display: inline-block;\n";

  webSite+="font-size: 168px;\n";

  webSite+="display:block;\n";

  webSite+="margin:0 auto;\n";

  webSite+="margin-top:130px;\n";

  webSite+="cursor: pointer;\n";

  webSite+="width:440px;\n";

  webSite+="height:400px;\n";

  webSite+="}\n";





  

  webSite+="p.thicker{font-weight:900;}\n";

  webSite+="#runtime{font-weight:900; font-size: 147%; color:RED;}\n";

  webSite+="</style>\n";

  webSite+="<BODY bgcolor=\'#E6E6FA\' onload=\'process()\'>\n";

    

  //webSite+="<div>Change the state of LED! </div>\n";

  webSite+="<button onClick=\'RunButtonWasClicked()\' id=\'button\'></button> &emsp;";

  

  



  webSite+="</BODY>\n";

  webSite+="</HTML>\n";

}



void buildJavascript(){

  javaScript="<SCRIPT>\n";

  

  javaScript+="var xmlHttp=createXmlHttpObject();\n";

  javaScript+="function createXmlHttpObject(){\n";

  javaScript+=" if(window.XMLHttpRequest){\n";

  javaScript+="    xmlHttp=new XMLHttpRequest();\n";

  javaScript+=" }else{\n";

  javaScript+="    xmlHttp=new ActiveXObject(\'Microsoft.XMLHTTP\');\n";

  javaScript+=" }\n";

  javaScript+=" return xmlHttp;\n";

  javaScript+="}\n";

  

  javaScript+="var click;\n";

  

  javaScript+="function handleServerResponse(){\n";

  javaScript+="   xmlResponse=xmlHttp.responseXML;\n";

  javaScript+="   xmldoc = xmlResponse.getElementsByTagName(\'response\');\n";

  javaScript+="   message = xmldoc[0].firstChild.nodeValue;\n";

  javaScript+="if(message == 1){click = 1; message = \'ON\'; document.getElementById(\'button\').style.background=\'#FFA200\';}else{click=0; message=\'OFF\'; document.getElementById(\'button\').style.background=\'#111111\';}\n";

  javaScript+="   document.getElementById(\'button\').innerHTML=message;\n";

  javaScript+="}\n";



  javaScript+="function process(){\n";

  javaScript+="   xmlHttp.open(\'PUT\',\'xml\',true);\n";

  javaScript+="   xmlHttp.onreadystatechange=handleServerResponse;\n"; // no brackets?????

  javaScript+="   xmlHttp.send(null);\n";

  javaScript+=" setTimeout(\'process()\',200);\n";

  javaScript+="}\n";



  javaScript+="function process2(){\n";

  javaScript+="    xmlHttp.open(\'SET\',\'set1ESPval?Start=\'+click,true);\n";

  javaScript+="    xmlHttp.send(null);\n";

  javaScript+=" setTimeout(\'process2()\',400);\n";

  javaScript+="}\n";



  javaScript+="function RunButtonWasClicked(){\n";

  javaScript+="click = (click==1)?0:1;\n";

  javaScript+="    xmlHttp.open(\'SET\',\'set1ESPval?Start=\'+click,true);\n";

  javaScript+="    xmlHttp.send(null);\n";

  javaScript+="}\n";       



  javaScript+="</SCRIPT>\n";

}

uint16_t x;

String data;

void buildXML(){

  XML="<?xml version=\'1.0\'?>";

  XML+="<response>";

  XML+=data;

  XML+="</response>";

}





void handleWebsite(){

  buildWebsite();

  server.send(200,"text/html",webSite);

}



void handleXML(){

  buildXML();

  server.send(200,"text/xml",XML);

}



void handle1ESPval(){

  start = server.arg("Start").toFloat();

 // Serial.println(start);

 // buildXML();

 // server.send(200,"text/xml",XML);



}

int start2=0;



int inc=0;



void setup() {



 

  Serial.begin(9600);  

  WiFi.begin(ssid,password);

  while(WiFi.status()!=WL_CONNECTED)delay(500);

  WiFi.mode(WIFI_STA);

  Serial.println("\n\nBOOTING ESP8266 ...");

  Serial.print("Connected to ");

  Serial.println(ssid);

  Serial.print("Station IP address: ");

  Serial.println(WiFi.localIP());

  server.on("/",handleWebsite);

  server.on("/xml",handleXML);

  server.on("/set1ESPval",handle1ESPval);

  

  server.begin();  

  pinMode(LED,OUTPUT);



}



void loop() {



    digitalWrite(LED,!start);

  //  Serial.println(start);

    data =(String)start;

    server.handleClient();

} 

Long polling in communication with Ajax generates traffic for wifi. In this case it is not good for ESP8266. We will solve this problem with WebSocket technology. Websocker is a full duplex protocol and does not send data over long polls, such as ajax. Toggles connection data connection on / off. Thus traffic is reduced. The following code is an example written with WebSocket technology.

#include <ESP8266WiFi.h>

#include <WebSocketsServer.h>

#include <WiFiClient.h>

#include <ESP8266WebServer.h>



//SSID and Password to your ESP Access Point

//const char* ssid = "ESPWebServer";

//const char* password = "12345678";



const char* ssid= "Newton" ;

const char* password= "X1t3q567ZO.#";  



int LED=2;                              // PINnumber where your LED is

int websockMillis=50;                    // SocketVariables are sent to client every 50 milliseconds

int sliderVal=60;           

byte brightness;

int c;

int inPin = D9 ;

char data[10];

int i;

ESP8266WebServer server(80); //Server on port 80

WebSocketsServer webSocket=WebSocketsServer(88);

String javaScript,JSONtxt;

unsigned long websockCount=1,wait000=0UL,wait001=0UL;

int LEDmillis=9*(100-sliderVal)+100;

boolean LEDonoff=true;



const char webSite[] PROGMEM = // #xxxxxxxx# are later to be changed in c function WebsiteContent()

R"=====(

    <!DOCTYPE HTML><HTML>

    <META name=\'viewport\' content=\'width=device-width, initial-scale=1\'>

    <html>

      <style>

        .box{

          position:relative;

          float:left;

          margin-right:10px;

          margin-bottom:10px;

          font-size:216%;

          font-weight: bold;

          width:65px;

          height:65px;

          border-radius: 50%;

          padding:5px;

          color:white;

          text-align:center;

          background-color:black;

          }



    </style>

  <body>

  </body>



<SCRIPT>







for (var i = 0;i < 200; i++) 

{

var divTag = document.createElement("div");

divTag.id = "kutu"+(i+1);

divTag.className = \'box\';

//divTag1.appendChild(divTag);

document.body.appendChild(divTag);

document.getElementById("kutu"+(i+1)).innerHTML = i+1;

}

  var data,datb; 

  InitWebSocket();

  function InitWebSocket(){

  websock=new WebSocket(\'ws://\'+window.location.hostname+\':88/\');

  websock.onmessage=function(evt){

  JSONobj=JSON.parse(evt.data);  

  data = (JSONobj.box1); 

  for(var i = 1; i <33; i++){

  datb = data>>(i-1) & 0x01; 

  if(datb == 1){document.getElementById("kutu" + i).style.background=\'#ADFF2F\'}else{document.getElementById("kutu" + i).style=\'background-color:black;\';} 

  }

 }

}

  </SCRIPT>

  </html>     

)=====";



void buildWebsite()

{

}

void buildJavascript()

{

}

String millis2time()

{

  String Time="";

  unsigned long ss;

  byte mm,hh;

  ss=millis()/1000;

  hh=ss/3600;

  mm=(ss-hh*3600)/60;

  ss=(ss-hh*3600)-mm*60;

  if(hh<10)Time+="0";

  Time+=(String)hh+":";

  if(mm<10)Time+="0";

  Time+=(String)mm+":";

  if(ss<10)Time+="0";

  Time+=(String)ss;

  return Time;

}



void handleWebsite()

{

  buildWebsite();

  server.send(200,"text/html",webSite);

}



void webSocketEvent(uint8_t num, WStype_t type, uint8_t * payload, size_t wslength)

{

  String payloadString=(const char *)payload;

  Serial.println(payloadString);

  //Serial.println("payload: \'"+payloadString+"\', channel: "+(String)num);

  if(type==WStype_TEXT){

  byte separator=payloadString.indexOf(\'=\');

  String var=payloadString.substring(0,separator);

  String val=payloadString.substring(separator+1);

  if(var=="LEDonoff"){

  LEDonoff=false;

  if(val=="ON")LEDonoff=true;

  digitalWrite(LED,HIGH);

  }else if(var=="sliderVal"){

  sliderVal=val.toInt();

  LEDmillis=9*(100-sliderVal)+100;

  }

  }

}



//                  SETUP

//===============================================================

void setup(void)

{

  Serial.begin(115200);

  Serial.println("");

  //WiFi.mode(WIFI_AP); //Only Access point

  WiFi.mode(WIFI_STA);

  //Start HOTspot removing password will disable security

  //WiFi.softAP(ssid, password);

  WiFi.begin(ssid,password);

  while(WiFi.status()!=WL_CONNECTED)delay(500);

  //IPAddress myIP = WiFi.softAPIP(); //Get IP address

  // Serial.print("HotSpt IP:");

  //Serial.println(myIP);

               

  WiFi.mode(WIFI_STA);

  Serial.println("\n\nBOOTING ESP8266 ...");

  Serial.print("Connected to ");

  Serial.println(ssid);

  Serial.print("Station IP address = ");

  Serial.println(WiFi.localIP());

 

  server.on("/",handleWebsite);

  server.begin();

  webSocket.begin();

  webSocket.onEvent(webSocketEvent);



  websockCount = 1;

}



char led1=0;

char veri;

char counter =0;



unsigned int senData = 0;

void loop(void)

{  

    webSocket.loop();

    server.handleClient();

    String LEDswitch="OFF";







    LEDonoff = veri & 0x01;

    if(millis()>wait001)

    {

    websockCount++;



  // websockCount = websockCount << 1;

  //  Serial.println(websockCount);

    senData = websockCount;

    String LEDswitch="LED = OFF";

    if(LEDonoff==true)LEDswitch="LED = ON";

    JSONtxt="{\"box1\":\""+(String)(senData & 0xFFFFFFFF)+"\"}";

    webSocket.broadcastTXT(JSONtxt);

    wait001=millis()+websockMillis;

  }

  }	

Video for the websocket will be added. Here is the thing, do not use pure html and css to desing the website, use javascript which saves more lines that means less traffic. It saves the time for your esp8266. 03/06/2018..

Leave a Comment

Your email address will not be published. Required fields are marked *