1

I want to use ESP8266 to parses the data on my site and performs the switching on / off of the led. It's a simple JSON file, but the code still doesn't get it to read. I have trid my best but still can't solve the problem. What could be the problem?

#include "WiFiEsp.h"
#include<ArduinoJson.h>

#ifndef HAVE_HWSERIAL1
#include "SoftwareSerial.h"
SoftwareSerial Serial1(12, 13); // RX, TX
#endif

char ssid[] = "mywifi";            // your network SSID (name)
char pass[] = "12345678";        // your network password
int status = WL_IDLE_STATUS;     // the Wifi radio's status

char server[] = "192.168.1.10";//192.168.1.10/arduino_light/light.json
String path = "/arduino_light/light.json"; //

unsigned long lastConnectionTime = 0;         // last time you connected to the server, in milliseconds
const unsigned long postingInterval = 20000L; // delay between updates, in milliseconds

// Initialize the Ethernet client object
WiFiEspClient client;

void setup()
{
  // initialize serial for debugging
  Serial.begin(9600);
  // initialize serial for ESP module
  Serial1.begin(9600);
  // initialize ESP module
  WiFi.init(&Serial1);

  // check for the presence of the shield
  if (WiFi.status() == WL_NO_SHIELD) {
    Serial.println("WiFi shield not present");
    // don't continue
    while (true);
  }

  // attempt to connect to WiFi network
  while ( status != WL_CONNECTED) {
    Serial.print("Attempting to connect to WPA SSID: ");
    Serial.println(ssid);
    // Connect to WPA/WPA2 network
    status = WiFi.begin(ssid, pass);
  }

  Serial.println("You're connected to the network");
}

void loop()
{
  // if there's incoming data from the net connection send it out the serial port
  // this is for debugging purposes only
  while (client.available()) {
    char c = client.read();
    Serial.write(c);
  }

  if (millis() - lastConnectionTime > postingInterval) {
    httpRequest();
  }
}

// this method makes a HTTP connection to the server
void httpRequest()
{
  Serial.println();

  // close any connection before send a new request
  // this will free the socket on the WiFi shield
  client.stop();

  // if there's a successful connection
  if (client.connect(server, 80)) {
    Serial.println("Connecting...");

    client.print(String("GET ") + 
    path + 
    " HTTP/1.1\r\n" + 
    "Host: " + server + "\r\n" + 
    "Connection: keep-alive\r\n\r\n");

    delay(1000); // wait for server to respond

    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }

    // read response  
    String section="header";
    while(client.available()){
      String line = client.readStringUntil('\r');
      Serial.println("line:"+line);    // we’ll parse the HTML body here
      if (section=="header") { // headers..
        if (line=="\n") { // skips the empty space at the beginning
           section="json";
        }
      } else if (section=="json") {  // print the good stuff
        section="ignore";
        String result = line.substring(1);      // Parse JSON
        int size = result.length() + 1;
        char json[size];
        result.toCharArray(json, size);
        StaticJsonBuffer<200> jsonBuffer;
        JsonObject& json_parsed = jsonBuffer.parseObject(json);
        if (!json_parsed.success())
        {
          Serial.println("parseObject() failed");
          return;
        }
        // Make the decision to turn off or on the LED
        if (strcmp(json_parsed["light"], "on") == 0) {
           Serial.println("LED ON");
        }
        else {
          Serial.println("led off");
        }
      }
      // note the time that the connection was made
      lastConnectionTime = millis();
    }
  } else {
    // if you couldn't make a connection
    Serial.println("Connection failed");
    delay(500);
  }
}

File path: 192.168.1.10/arduino_light/light.json

File content: {"light": "on"}

Result:

[WiFiEsp] Disconnecting  3
[WiFiEsp] Connecting to 192.168.1.10
Connecting...
line:HTTP/1.1 200 OK
line:
Server: nginx
[WiFiEsp] TIMEOUT: 220
line:

1 Answer 1

0

I think.. you take a look the response to HTTP protocol:

HTTP/1.1 200 OK\r\n
[header]\r\n
[header]\r\n
[header]\r\n\r\n
[body]...

If you get JSON body use this code

String line = client.readStringUntil('}');

or

while (client.connected()) {
    if (client.available()) {
        c = client.read();
        Serial.print(c);
    }
}

and parsing the response

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.