2

There is a code for ESP8266, which parses the data on my site and performs the switching on / off of the led. When it was a static JSON file, it all worked without problems. But when I transferred a file to PHP that dynamically updates the data and displays it in JSON format, the script doesn't get it to read. What could be the problem?

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#define pin 5

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

const char* host     = "www.site.ru"; // domain  
String path          = "/lightAPI.php";  

void setup() {  
  pinMode(pin, OUTPUT); 
  pinMode(pin, HIGH);
  digitalWrite(5, HIGH);
  Serial.begin(9600);

  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("WiFi connected");  
  Serial.println("IP address: " + WiFi.localIP());
}

void loop() {  
  WiFiClient client;
  const int httpPort = 80;
  if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
  }

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


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

  // read response
  String section="header";
  while(client.available()){
    String line = client.readStringUntil('\r');
    // Serial.print(line);
    // we’ll parse the HTML body here
    if (section=="header") { // headers..
      Serial.print("");
      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"], "OFF") == 0) {
        digitalWrite(5, HIGH); 
        Serial.println("LED OFF");
      }
      else {
        digitalWrite(5, LOW);
        Serial.println("LED ON");
      }
    }
  }
}

PHP file

<?php
header('Content-Type: application/json');
$status = file_get_contents('txt/lightStatus.txt');

$json = array('light' => $status, 'time' => date("G"));

echo json_encode($json);
?>
4
  • Did you try opening that PHP in a browser? Did you try printing that JSON string to serial? And where exactly does your code fail? Commented Jun 16, 2017 at 14:33
  • @gre_gor, Yes, it prints a JSON string in the browser, as it should. If I copy this string into a .json file, then ESP reads it. Displays the error parseObject () failed Commented Jun 16, 2017 at 15:26
  • Is it possible that your hosting service is adding something to your PHP file? Some tracking code or ads? Check that out carefully (check the source code of your website in your browser (CTRL+U in Chrome) - maybe there's something hidden that is not being displayed). Also, what is your content of lightStatus.txt? Mine is simply OFF. I run your code on my ESP8266 and XAMPP server and it's working alright. Commented Jun 17, 2017 at 12:05
  • @Defozo, In lightStatus.tht only the ON / OFF state. I checked the code and in chrome it does not add anything, just JSON. You can check yourself bot.erm.today/lightAPI.php . Commented Jun 17, 2017 at 12:18

2 Answers 2

1

There's something wrong with handling the response. It works when connecting to my server but it doesn't work when connecting to yours.

This is what ESP8266 gets when connecting to my server:

HTTP/1.1 200 OK
Date: Sat, 17 Jun 2017 18:21:37 GMT
Server: Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.19
X-Powered-By: PHP/5.6.19
Content-Length: 31
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: application/json

{"light":"OFF","time":"20"}

And this is what it gets when connecting to yours:

HTTP/1.1 200 OK
Server: nginx admin
Date: Sat, 17 Jun 2017 18:25:53 GMT
Content-Type: application/json
Transfer-Encoding: chunked
Connection: keep-alive

28
{"light":"OFF","online":"0","time":"21"}
0

Unfortunately, I don't have time now to investigate the problem with your code but meanwhile here is a working one which uses HTTPClient to handle request and response (I would recommend using this anyway):

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ArduinoJson.h>
#define pin 5

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

void setup() {  
  pinMode(pin, OUTPUT); 
  pinMode(pin, HIGH);
  digitalWrite(5, HIGH);
  Serial.begin(9600);

  delay(10);
  Serial.print("Connecting to ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);
  int wifi_ctr = 0;
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("WiFi connected");  
  Serial.println("IP address: " + WiFi.localIP());
}

void loop() {  
  HTTPClient http;
  http.begin("http://bot.erm.today/lightAPI.php");
  int statusCode = http.GET();
  StaticJsonBuffer<200> jsonBuffer;
  JsonObject& json_parsed = jsonBuffer.parseObject(http.getString());
  http.end();
  if (!json_parsed.success())
  {
    Serial.println("parseObject() failed");
    return;
  }

  // Make the decision to turn off or on the LED
  if (strcmp(json_parsed["light"], "OFF") == 0) {
    digitalWrite(5, HIGH); 
    Serial.println("LED OFF");
  }
  else {
    digitalWrite(5, LOW);
    Serial.println("LED ON");
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Super explained in here.
0

Json is simply a format, a structure, it needs no processing. PHP on the other hand is a server side language that means that is is interpreted by another application and it is actually that application that is interpreting the code that does the work. The esp8266 lacks that application. And will not be able to run your PHP file. I would recommend looking into making an API in php that is stored on a server somewhere and have your esp call out to that. Or see if you can implement your code right on the esp, though you may be limited by CPU, memory, and processing power. Good luck!

2 Comments

He is not trying to run a PHP file on an ESP8266. He is trying to parse JSON generated by a PHP file.
Ahh, Sorry I miss understood the question

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.