Arduino Iot Project parseObject() failed

0

I'm trying to control 8 channel relay with esp8266. and i've been following this tutorial on youtube Creating your own IoT Cloud from scratch using php, mysql and NodeMCU (ESP12E or ESP8266) - Part 4 - YouTube I did exactly what the guy said. I uploaded my code to Arduino but I get a "parseObject() failed" error on the serial monitor. I don't really understand coding much so I wonder if you guys help me out with my project.(the only thing I couldn't do was to change my web host PHP version to 5.2, I use 5.3.29- obsolete)

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;
int delays[] = {150,300,300,100,300,550,575,};
int Tone1[] = {660,660,660,510,660,770,380,};
int Tone2[] = {100,100,100,100,100,100,100,};
const char* ssid     = "ASUS 2.4GHZ";
const char* password = "mywifipassword";
const char* host = "falconiot.atwebpages.com"; 
String url;
  int i =0;
  int count = 0;
  int panjur1_status = 1;
  int panjur2_status = 1;
  String url2 = "/api/relays/update.php?id=8&status=on";
void setup() {
   for(int a = 0; i < 7; i++){
    tone(D0, Tone1[i], Tone2[i]);
    delay(delays[i]);}
  Serial.begin(115200);
  delay(100);
  pinMode(D0, INPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);
  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(D4, LOW);
  digitalWrite(D5, LOW);
  digitalWrite(D6, LOW);
  digitalWrite(D7, LOW);
  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");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Netmask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
}

 void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

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

  if (count == 0){
    url = "/api/relays/read_all.php?id=1";
    count = count + 1;
    Serial.println("Here1");
  }
  else if (count == 1){
    url = "/api/relays/read_all.php?id=2";
    count = count + 1;
    Serial.println("Here2");
  }
  else if (count == 2){
    url = "/api/relays/read_all.php?id=3";
    count = count + 1;
    Serial.println("Here3");
  }
  else if (count == 3){
    url = "/api/relays/read_all.php?id=4";
    count = count + 1;
    Serial.println("Here4");
  }
  else if (count == 4){
    url = "/api/relays/read_all.php?id=5";
    count = count + 1;
    Serial.println("Here5");
  }
  else if (count == 5){
    url = "/api/relays/read_all.php?id=6";
    count = count + 1;
    Serial.println("Here6");
  }
  else if (count == 6){
    url = "/api/relays/read_all.php?id=7";
    count = count + 1;
    Serial.println("Here7");
  }
  Serial.print("Requesting URL: ");
  Serial.println(url);

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(500);
  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..

      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<400> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      String relay = json_parsed["relay"][0]["status"];

           if(count == 1){
        if(relay == "on" && panjur1_status == 1){
          digitalWrite(D1, LOW);
          delay(30000);
          digitalWrite(D1, HIGH);
          panjur1_status = 0;
          Serial.println("D1 is On..!");
        }
        else if(relay == "off" && panjur1_status == 0){
          digitalWrite(D2, LOW);
          delay(30000);
          digitalWrite(D2, HIGH);
          panjur1_status=1;
          Serial.println("D2 is Off..!");
        }
      }
      else if(count == 2){
       if(relay == "on" && panjur2_status == 1){
          digitalWrite(D3, LOW);
          delay(30000);
          digitalWrite(D3, HIGH);
          panjur2_status = 0;
          Serial.println("D3 is On..!");
        }
       if(relay == "on" && panjur2_status == 1){
          digitalWrite(D4, LOW);
          delay(30000);
          digitalWrite(D4, HIGH);
          panjur2_status = 1;
          Serial.println("D4 is Off..!");
        }
      }
       else if(count == 3){
        if(relay == "on"){
          digitalWrite(D5, LOW);
          Serial.println("D5 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D5, HIGH);
          Serial.println("D5 is Off..!");
        }
      }
       else if(count == 4){
        if(relay == "on"){
          digitalWrite(D6, LOW);
          Serial.println("D6 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D6, HIGH);
          Serial.println("D6 is Off..!");
        }
      }
      else if(count == 5){
        if(relay == "on"){
          digitalWrite(D7, LOW);
          Serial.println("D7 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D7, HIGH);
          Serial.println("D7 is Off..!");
        }
      }
       else if(count == 6){
        if(relay == "on"){
          digitalWrite(D8, 1);
          Serial.println("D8 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D8, 0);
          Serial.println("D8 is Off..!");
        }
      }
      else if(count == 7){
        if(relay == "on"){
          if(D0==HIGH){
            digitalWrite(D8,HIGH);
            delay(50);
            digitalWrite(D8,LOW);
            delay(50);
            client.print(String("GET ") + url2 + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(500);
            }
          Serial.println("PIR Working!");
        }
        else if(relay == "off"){
          digitalWrite(D8, 0);
          Serial.println("PIR Is Not Wokring!");
        }
        count = 0;
      }

      if (count == 8)
        count = 0;


    }
  }
  Serial.println();
  Serial.println("closing connection");
  delay(5000);
}
        result.toCharArray(json, size);
      StaticJsonBuffer<400> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      }

This is where the message is coming from

At a guess the json array derived from the result variable is not valid. Have you tried printing the result variable to see what it looks like ?

Well, I'm not sure how to do that. As I said I don't understand coding stuff much. Can you help me, please?

edit:http://falconiot.atwebpages.com/api/relays/read_all.php?id=1 is this what you asked for ?

Please post what you tried here rather than on a web site

Sorry about that, you are right.

{"success":1,"relays":[{"id":"1","status":"off"}]}

this is the message delivered from my website when you click that url.

I know little or nothing about JSON

Is that a valid JSON message ?

This is the php code that generates this message. I think it is a JSON message.

<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

//Creating Array for JSON response
$response = array();
 
// Include data base connect class
$filepath = realpath (dirname(__FILE__));
require_once($filepath."/db_connect.php");

 // Connecting to database
$db = new DB_CONNECT();
 
// Check if we got the field from the user
if (isset($_GET["id"])) {
    $id = $_GET['id'];
 
     // Fire SQL query to get relays data by id
    $result = mysql_query("SELECT *FROM relays WHERE id = '$id'");
	
	//If returned result is not empty
    if (!empty($result)) {

        // Check for succesfull execution of query and no results found
        if (mysql_num_rows($result) > 0) {
			
			// Storing the returned array in response
            $result = mysql_fetch_array($result);
			
			// temperoary user array
            $led = array();
            $led["id"] = $result["id"];
            $led["status"] = $result["status"];
          
            $response["success"] = 1;

            $response["relays"] = array();
			
			// Push all the items 
            array_push($response["relays"], $led);
 
            // Show JSON response
            echo json_encode($response);
        } else {
            // If no data is found
            $response["success"] = 0;
            $response["message"] = "No data on relays found";
 
            // Show JSON response
            echo json_encode($response);
        }
    } else {
        // If no data is found
        $response["success"] = 0;
        $response["message"] = "No data on relays found";
 
        // Show JSON response
        echo json_encode($response);
    }
} else {
    // If required parameter is missing
    $response["success"] = 0;
    $response["message"] = "Parameter(s) are missing. Please check the request";
 
    // echoing JSON response
    echo json_encode($response);
}
?>
     // Fire SQL query to get weather data by id
    $result = mysql_query("SELECT *FROM relays WHERE id = '$id'");

You store weather data in a database called relays?

From what I can see, you have two values to return - id and status. I can't see any reason for encoding that tiny amount of data as json data. Just echo id, a comma, and status. Parsing that on the Arduino will be trivial.

Even easier would be to echo '[', id, a comma, status, and ']', and find Robin2's Serial Input Basics thread.

The program runs but I get parseObject() failed error in the serial monitor.

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
static const uint8_t D0   = 16;
static const uint8_t D1   = 5;
static const uint8_t D2   = 4;
static const uint8_t D3   = 0;
static const uint8_t D4   = 2;
static const uint8_t D5   = 14;
static const uint8_t D6   = 12;
static const uint8_t D7   = 13;
static const uint8_t D8   = 15;
static const uint8_t D9   = 3;
static const uint8_t D10  = 1;
int delays[] = {150,300,300,100,300,550,575,};
int Tone1[] = {660,660,660,510,660,770,380,};
int Tone2[] = {100,100,100,100,100,100,100,};
const char* ssid     = "ASUS 2.4GHZ";
const char* password = "A45CB547CBDB6A32";
const char* host = "falconiot.atwebpages.com"; //replace it with your webhost url
String url;
  int i =0;
  int count = 0;
  int panjur1_status = 1;
  int panjur2_status = 1;
  String url2 = "/api/relays/update.php?id=8&status=on";
void setup() {
   for(int a = 0; i < 7; i++){
    tone(D0, Tone1[i], Tone2[i]);
    delay(delays[i]);}
  Serial.begin(115200);
  delay(100);
  pinMode(D0, INPUT);
  pinMode(D1, OUTPUT);
  pinMode(D2, OUTPUT);
  pinMode(D3, OUTPUT);
  pinMode(D4, OUTPUT);
  pinMode(D5, OUTPUT);
  pinMode(D6, OUTPUT);
  pinMode(D7, OUTPUT);
  pinMode(D8, OUTPUT);
  digitalWrite(D1, LOW);
  digitalWrite(D2, LOW);
  digitalWrite(D3, LOW);
  digitalWrite(D4, LOW);
  digitalWrite(D5, LOW);
  digitalWrite(D6, LOW);
  digitalWrite(D7, LOW);
  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");  
  Serial.println("IP address: ");
  Serial.println(WiFi.localIP());
  Serial.print("Netmask: ");
  Serial.println(WiFi.subnetMask());
  Serial.print("Gateway: ");
  Serial.println(WiFi.gatewayIP());
}
 
 void loop() {

  Serial.print("connecting to ");
  Serial.println(host);

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

  if (count == 0){
    url = "/api/relays/read_all.php?id=1";
    count = count + 1;
    Serial.println("Here1");
  }
  else if (count == 1){
    url = "/api/relays/read_all.php?id=2";
    count = count + 1;
    Serial.println("Here2");
  }
  else if (count == 2){
    url = "/api/relays/read_all.php?id=3";
    count = count + 1;
    Serial.println("Here3");
  }
  else if (count == 3){
    url = "/api/relays/read_all.php?id=4";
    count = count + 1;
    Serial.println("Here4");
  }
  else if (count == 4){
    url = "/api/relays/read_all.php?id=5";
    count = count + 1;
    Serial.println("Here5");
  }
  else if (count == 5){
    url = "/api/relays/read_all.php?id=6";
    count = count + 1;
    Serial.println("Here6");
  }
  else if (count == 6){
    url = "/api/relays/read_all.php?id=7";
    count = count + 1;
    Serial.println("Here7");
  }
  Serial.print("Requesting URL: ");
  Serial.println(url);
  
  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(500);
  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..
     
      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<400> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      String relay = json_parsed["relay"][0]["status"];
      Serial.println("DATA");
      Serial.println(relay);

           if(count == 1){
        if(relay == "on" && panjur1_status == 1){
          digitalWrite(D1, LOW);
          delay(30000);
          digitalWrite(D1, HIGH);
          panjur1_status = 0;
          Serial.println("D1 is On..!");
        }
        else if(relay == "off" && panjur1_status == 0){
          digitalWrite(D2, LOW);
          delay(30000);
          digitalWrite(D2, HIGH);
          panjur1_status=1;
          Serial.println("D2 is Off..!");
        }
      }
      else if(count == 2){
       if(relay == "on" && panjur2_status == 1){
          digitalWrite(D3, LOW);
          delay(30000);
          digitalWrite(D3, HIGH);
          panjur2_status = 0;
          Serial.println("D3 is On..!");
        }
       if(relay == "on" && panjur2_status == 1){
          digitalWrite(D4, LOW);
          delay(30000);
          digitalWrite(D4, HIGH);
          panjur2_status = 1;
          Serial.println("D4 is Off..!");
        }
      }
       else if(count == 3){
        if(relay == "on"){
          digitalWrite(D5, LOW);
          Serial.println("D5 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D5, HIGH);
          Serial.println("D5 is Off..!");
        }
      }
       else if(count == 4){
        if(relay == "on"){
          digitalWrite(D6, LOW);
          Serial.println("D6 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D6, HIGH);
          Serial.println("D6 is Off..!");
        }
      }
      else if(count == 5){
        if(relay == "on"){
          digitalWrite(D7, LOW);
          Serial.println("D7 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D7, HIGH);
          Serial.println("D7 is Off..!");
        }
      }
       else if(count == 6){
        if(relay == "on"){
          digitalWrite(D8, 1);
          Serial.println("D8 is On..!");
        }
        else if(relay == "off"){
          digitalWrite(D8, 0);
          Serial.println("D8 is Off..!");
        }
      }
      else if(count == 7){
        if(relay == "on"){
          if(D0==HIGH){
            digitalWrite(D8,HIGH);
            delay(50);
            digitalWrite(D8,LOW);
            delay(50);
            client.print(String("GET ") + url2 + " HTTP/1.1\r\n" +
               "Host: " + host + "\r\n" + 
               "Connection: close\r\n\r\n");
  delay(500);
            }
          Serial.println("PIR Working!");
        }
        else if(relay == "off"){
          digitalWrite(D8, 0);
          Serial.println("PIR Is Not Wokring!");
        }
        count = 0;
      }

      if (count == 8)
        count = 0;


    }
  }
  Serial.println();
  Serial.println("closing connection");
  delay(5000);
}

Serial Monitor:

WiFi connected
IP address: 
192.168.0.15
Netmask: 255.255.255.0
Gateway: 192.168.0.1
connecting to falconiot.atwebpages.com
Here1
Requesting URL: /api/relays/read_all.php?id=1
parseObject() failed
connecting to falconiot.atwebpages.com
Here2
Requesting URL: /api/relays/read_all.php?id=2
parseObject() failed
connecting to falconiot.atwebpages.com
Here3
Requesting URL: /api/relays/read_all.php?id=3
parseObject() failed
connecting to falconiot.atwebpages.com
Here4
Requesting URL: /api/relays/read_all.php?id=4
parseObject() failed
connecting to falconiot.atwebpages.com
Here5
Requesting URL: /api/relays/read_all.php?id=5
parseObject() failed
connecting to falconiot.atwebpages.com
Here6
Requesting URL: /api/relays/read_all.php?id=6
parseObject() failed
connecting to falconiot.atwebpages.com
Here7
Requesting URL: /api/relays/read_all.php?id=7
parseObject() failed
connecting to falconiot.atwebpages.com
Requesting URL: /api/relays/read_all.php?id=7
parseObject() failed
connecting to falconiot.atwebpages.com
Requesting URL: /api/relays/read_all.php?id=7
parseObject() failed
connecting to falconiot.atwebpages.com
Requesting URL: /api/relays/read_all.php?id=7

this is the JSON text:

{"success":1,"relays":[{"id":"2","status":"on"}]}

Another thread on the same topic? Why?

Because no one really helped me also I couldn't find to remove the old one.

I wish I could help you more. I have messed with JSON some on web applications but not on microcontrollers.

I do see a simple example posted arduinojosn.org

char json[] = "{\"hello\":\"world\"}";
StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.parseObject(json);
const char* world = object["hello"];
  1. Have you tried just parsing a simple JSON string like this example and verify it works? You could just hard code it here
 // Parse JSON
      //int size = result.length() + 1;
      //char json[size];
      //result.toCharArray(json, size);
      char json[] = "{\"hello\":\"world\"}";
      StaticJsonBuffer<400> jsonBuffer;
      JsonObject& json_parsed = jsonBuffer.parseObject(json);

and see if it will properly parse the simpler JSON object. That will give you some indication of what's going on.

  1. Are you properly escaping the double quotes like in the example? I see you have double quotes around your keys and some of your values. I'm only mentioning this because the example explicitly shows escaping all double quotes within the string.

Hope this helps!

Duplicate topics merged

Cross-posting is against the rules of the forum. The reason is that duplicate posts can waste the time of the people trying to help. Someone might spend 15 minutes (or more) writing a detailed answer on this topic, without knowing that someone else already did the same in the other topic.

Repeated cross-posting will result in a suspension from the forum.

In the future, please take some time to pick the forum board that best suits the topic of your question and then only post once to that forum board. This is basic forum etiquette, as explained in the sticky "How to use this forum - please read." post you will find at the top of every forum board. It contains a lot of other useful information. Please read it.

Thanks in advance for your cooperation.

davie_gravy:
I wish I could help you more. I have messed with JSON some on web applications but not on microcontrollers.

I do see a simple example posted arduinojosn.org

char json[] = "{\"hello\":\"world\"}";

StaticJsonBuffer<200> jsonBuffer;
JsonObject& object = jsonBuffer.parseObject(json);
const char* world = object["hello"];




1) Have you tried just parsing a simple JSON string like this example and verify it works? You could just hard code it here


// Parse JSON
     //int size = result.length() + 1;
     //char json[size];
     //result.toCharArray(json, size);
     char json[] = "{"hello":"world"}";
     StaticJsonBuffer<400> jsonBuffer;
     JsonObject& json_parsed = jsonBuffer.parseObject(json);



and see if it will properly parse the simpler JSON object. That will give you some indication of what's going on.

2) Are you properly escaping the double quotes like in the example? I see you have double quotes around your keys and some of your values. I'm only mentioning this because the example explicitly shows escaping all double quotes within the string.

Hope this helps!

Thank you for your answer. I tried the example code in another program and it worked. So I changed my code. Now I don't get parseObject() failed but I don't get any result too.

 // Parse JSON
      StaticJsonBuffer<400> jsonBuffer;
      char json[] = "{\"success\":1,\"relays\":[{\"id\":\"2\",\"status\":\"on\"}]}";
      JsonObject& json_parsed = jsonBuffer.parseObject(json);
      if (!json_parsed.success())
      {
        Serial.println("parseObject() failed");
        return;
      }
      String led = json_parsed["relays"][0]["status"];
      Serial.println("Data From Web:");
      Serial.println(relay);

Serial Monitor:

Connecting to ASUS 2.4GHZ
.....
WiFi connected
IP address: 
192.168.0.15
Netmask: 255.255.255.0
Gateway: 192.168.0.1
connecting to falconiot.atwebpages.com
Here1
Requesting URL: /api/relays/read_all.php?id=1
DATA


closing connection
connecting to falconiot.atwebpages.com
Here2
Requesting URL: /api/relays/read_all.php?id=2
DATA


closing connection
connecting to falconiot.atwebpages.com
Here3
Requesting URL: /api/relays/read_all.php?id=3
DATA


closing connection
connecting to falconiot.atwebpages.com
Here4
Requesting URL: /api/relays/read_all.php?id=4
DATA


closing connection

The snippet of code you posted does not produce the output you showed.