Data bucket query, from a device


#1

I want to share with the community one way to recover a variable from a bucket, with a NodeMCU board, it can be done using two functions, one to ask to the bucket the last data, and other to extract the specific value from that response.

The link to execute the consult should be as the next, and it will return the last bucket value, change the fields [USERNAME], [BUCKET NAME] and [TOKEN] by yours, you can test with the browser to verify it is working

https://api.thinger.io/v1/users/[USERNAME]/buckets/[BUCKET NAME]/data?items=1&max_ts=0&sort=desc&authorization=[AUTH TOKEN]

Its needed to include the library

#include <ESP8266HTTPClient.h>

To recover the last saved item in bucket you can use the next function, just need to set as input the link to do the consult, it will return a string with the last saved item in the bucket

String httpRequest(String link)
{

  String payload;
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
 
    HTTPClient http;  //Declare an object of class HTTPClient
 
    http.begin(link);  //Specify request destination
    int httpCode = http.GET();                                                                  //Send the request
 
    if (httpCode > 0) { //Check the returning code
 
       payload = http.getString();   //Get the request response payload
  //    Serial.println(payload);                     //Print the response payload
 
    }
 
    http.end();   //Close connection
  }

return payload;
}

To extract a specific variable, can be used the next function, it needs as inputs the variable name (as is written in the bucket response) and the string where is going to be looked in (previous function response)

float varExtract(String varToExtract, String payload)
{
  int Start = payload.indexOf(varToExtract) + varToExtract.length(); + 2; 
  int End = payload.indexOf(",", Start);
    if (End<0) // Last variable doesnt have ',' at the end, have a ']'
    {
      End = payload.indexOf("]");
    }
  String stringVar = payload.substring(Start, End);
  float var = stringVar.toFloat();
  return var;
}

Look that it returns a float value, it can be changed to integer but is needed to change the last instruction from:

  float var = stringVar.toFloat();

to:

  int var = stringVar.toInt();

And, of course, the function declaration from:

float varExtract(String varToExtract, String payload)

to:

int varExtract(String varToExtract, String payload)

I’ve done in two different functions due it can be extracted from the same payload more than one variable, and its not efficient do one http request for each variable to recover, just need to call the extract function with the previous http response.

I dont know if there is a limitation about how often a bucket can be called, be careful about how you establish the call routine frequency in your code.