Close

ESP8266 direct access from web-app

A project log for Smart Home in the IoT Way

ESP8266 based humidity logging and adaptive fan control, door lock detector, and more...

x-labzx-labz 08/08/2016 at 10:440 Comments

In our case the user interface is implemented as a mobile web application, running on smartphone web browser.

The mobile client gets the sensor data from the cloud server, where the sensor nodes are sending their measurements. BUT, what if there is no Internet connection, or the cloud server is down? The mobile client is capable to connect directly the end nodes, only the local (WiFi) network is needed.

An important remark here: The mobile web client is set up to use the HTML5 application cache, so it is able to run off-line as well!

Each ESP8266 end-node runs a web client to send the sensor data to the cloud server, and a web-server to respond to the direct requests, and receive the commands or other configuration settings.

To access the ESP8266 web-servers the mobile app issues a so called Cross Domain Request (CORS) and the ESP8266 should respond to it in the proper way.

The CORS requests have two types:

This requests are served out-of-the-box with the servers implemented with the ESP8266WebServer library, as it automatically includes the response header:

Access-Control-Allow-Origin: * 

The ESP8266 code:

server.on("/", HTTP_OPTIONS, []() {
    server.sendHeader("Access-Control-Max-Age", "10000");
    server.sendHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
    server.sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    server.send(200, "text/plain", "" );
  });

server.on("/", HTTP_GET, []() {
    String response ;
    // ... some code to prepare the response data...

    server.sendHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS");
    server.sendHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    server.send(200, "text/plain", response.c_str() );
  });
In the case of non-simple CORS requests, obviously you can handle any other content type than "text/plain" e.g. JSON or XML, but the cost is the preflight request!

One more key factor: The HTML5 application cache is controlled by the CACHE MANIFEST and to make the CORS requests happen, you need to add the * wildcard in the NETWORK section:

NETWORK:
*

Discussions