Example sketches for the new Arduino IDE for ESP8266

Moderator: igrr

User avatar
By taikapanu
#64997 Hi,

I have been googling for few days now and can't just figure this out.

My goal is to buildt few ESP-12-F modules with different kinds of sensors and make them to send data in JSON. So step by step:
1. Go it ESP IP address with browser, lets say 192.168.2.25/
2. ESP would respond with JSON, like: {"humidity": "55","temperature": "22"}

This works with a google chrome but I can't get it working with javascript. I have been using Philips HUE API debug tool so it should be covered.

If I point the debug tool to the ESP IP address 192.168.2.25/ I get Error 404. But for comparison if I put this to the debugger "http://echo.jsontest.com/humidity/55/temperature/22" I get correct JSON response back.

Philips code below:
Code: Select all<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>API Debug tool</title>
        <style>
            body{
                font-family: verdana;
                margin: 20px;
            }
            h1{
                margin: 0px;
                font-size: 20px;
            }
            h2{
                font-size: 16px;
                margin-top: 20px;
                color: grey;
            }
            #buttons{
                clear: left;
            }
            input{
                width: 100%;
            }
            form{
                background: #e8e8e8;
                width: 500px;
                padding: 20px;
                -webkit-border-radius: 10px;
                -moz-border-radius: 10px;
            }
            textarea{
                padding-top: 10px;
                width: 100%;
                font-family: monaco,monospace;
                font-size: 12px;
                -webkit-border-radius: 10px;
                -moz-border-radius: 10px;
            }
        </style>
    </head>

    <body>
        <form name="commandform">
            <h1>CLIP API Debugger</h1>
            <h2>URL:</h2>
            <input name="commandurl" type="text" size="60" value="/api/1234/">
            <div id="buttons">
                <button type="button" onclick="getHTML('GET')">GET</button>
                <button type="button" onclick="getHTML('PUT')">PUT</button>
                <button type="button" onclick="getHTML('POST')">POST</button>
                <button type="button" onclick="getHTML('DELETE')">DELETE</button>
            </div>
            <h2>Message Body:</h2>
            <textarea name="messagebody" rows="10" cols="100"></textarea>
            <h2>Command Response:</h2>
            <textarea name="response" rows="25" cols="100"></textarea>
        </form>
    </body>
</html>

<script language="JavaScript">
function getHTML(command)
{
    if (window.XMLHttpRequest)
    {
        var http = new XMLHttpRequest();
        http.open(command, document.commandform.commandurl.value, true);

        http.onreadystatechange = function()
        {
            if(http.readyState == 4)
            {
                if(http.status==200)
                {
                    document.commandform.response.value="Bad JSON: "+http.responseText
                    document.commandform.response.value=JSON.stringify(JSON.parse(http.responseText), null, '\t');
                }
                else
                {
                    document.commandform.response.value="Error "+http.status
                }
            }
        }
        http.send(document.commandform.messagebody.value);
    }
    return false;
}
</script>


I tried this: viewtopic.php?f=29&t=7158
And it "works" but I have the same problem as the last two replies. My ESP posts the JSON back quite slowly and Philips HUE debugger doesn't receive it. I tried many other codes too, but I'm having huge troubles finding examples on how to repond to GET with JSON. There are many examples how to POST or GET JSON with ESP but in my case the GET is coming from somewhere else and the ESP should response with JSON.

I ran out of ideas what to do. Can someone point me to right direction or check what is my mistake? My ESP code below. Mostly copied from WifiWebServer example.
Code: Select all#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <SimpleDHT.h>

const char* ssid = "xxx";
const char* password = "xxx";

// Create an instance of the server
// specify the port to listen on as an argument
WiFiServer server(80);

int pinDHT11 = 16;
SimpleDHT11 dht11;
byte temperature = 0;
byte humidity = 0;
unsigned long timeForDHT=millis();

void setup() {
  Serial.begin(115200);
  delay(10);
 
  // Connect to WiFi network
  Serial.println();
  Serial.println();
  Serial.print("Connecting to ");
  Serial.println(ssid);
 
  WiFi.begin(ssid, password);
 
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }
  Serial.println("");
  Serial.println("WiFi connected");
 
  // Start the server
  server.begin();
  Serial.println("Server started");

  // Print the IP address
  Serial.println(WiFi.localIP());
}

void loop() {
    //Read temperatyre and humidity every one second
   
    if(millis() > timeForDHT + 1000)
    {
        if (dht11.read(pinDHT11, &temperature, &humidity, NULL))
        {
        Serial.print("Read DHT11 failed.");
        }
        //Serial.print((int)temperature); Serial.print(" *C, ");
        //Serial.print((int)humidity); Serial.println(" %");
        timeForDHT = millis();
    }
 
  // Check if a client has connected
  WiFiClient client = server.available();
  if (!client) {
    return;
  }
 
  // Wait until the client sends some data
  Serial.println("new client");
  while(!client.available()){
    delay(1);
  }
 
  // Read the first line of the request
  String req = client.readStringUntil('\r');
  Serial.println(req);
  client.flush();
 
  // Match the request
  if (req.indexOf("/") != -1)
  {
    }
  else {
    Serial.println("invalid request");
    client.stop();
    return;
  }


 
  client.flush();

  // Prepare the response
  String s = "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"IDkey\":\"ESP-1\",\"sensors\":{\"1\":{\"type\":\"humidity\",\"value\":0},\"2\":{\"type\":\"temperature\",\"value\":0},}}\r\n\r\n";


  // Send the response to the client
  client.print(s);
  delay(1);
  Serial.println("Client disonnected");

  // The client will actually be disconnected
  // when the function returns and 'client' object is detroyed
}
User avatar
By taikapanu
#65368 OK I figured it out..

I started to wonder why my request is going to c: drive. The code started to look for file named as ip from the folder where the HTML code was ran.

So easy fix, add http:// in front of IP in order to make it go to internet.....

Also, found that advanced webserver example was more stable. The one above got easily stuck.
https://github.com/esp8266/Arduino/tree ... dWebServer

-Juha