0

Using the Arduino IDE with the Nodemcu-esp12e module, I created a program which makes an HTTP GET request.

However, I do not know how it would be the right way to deal with the return of this consultation.

I am validating the return with the 'indexOf' function to find out if the return is false/off or true/on.

This is the correct way to validate the return?
Any suggestions for how to improve this code?

#include <ESP8266WiFi.h>
const char* ssid     = "mywifiid";
const char* password = "mypassword";
IPAddress host(192,168,0,11); 

void setup() {
  Serial.begin(115200);
  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());
}

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;
  }
  else{
    Serial.println("connection success");
  }
  //
  String get = "http://localhost/Test/GetStatusSensor?idsensor=2";
  Serial.println(get);
  //
  client.print("GET " + get + "\r\nHTTP/1.1\r\nHost: localhost\Test\r\nConnection: keep-alive\r\n\r\n");
  //
  while(client.available()){
    String line = client.readStringUntil('\r');
    //
    int iret= line.indexOf('on');
    //
    Serial.print(line);
    Serial.println(String(iret));
    //
    if (iret> 0) {
      //
      Serial.println("On");
    }
    else {
      Serial.println("Off");
    }    
  }
  //
  Serial.println();
  Serial.println("closing connection");
  delay(20000);  // 20 sec
}
too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Sr Julien
  • 494
  • 1
  • 8
  • 27

1 Answers1

1

My suggestion is to use JSON to switch to more structured way of comm. You can define custom data names and types and easily cover them. Take a look it at :

https://github.com/bblanchon/ArduinoJson

Here some JSON example from the HTTPClient example :

  DynamicJsonBuffer jsonBuffer(BUFFER_SIZE);

  JsonObject& root = jsonBuffer.parseObject(client);

  if (!root.success()) {
    Serial.println("JSON parsing failed!");
    return false;
  }

  // Here were copy the strings we're interested in
  strcpy(userData->name, root["name"]);
  strcpy(userData->company, root["company"]["name"]);
cagdas
  • 1,634
  • 2
  • 14
  • 27