Data bucket query, from a device

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

http://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.

2 Likes

There is a way to consult a resource from another device, with a link like this

It has a function to extract the specific variable you want to read, and I’ve checked and there is a way to consult a device resource and it will give you an answer as a json array

https://api.thinger.io/v2/users/[USER]/devices/[DEVICE]/[RESOURCE?authorization=[AUTH_TOKEN]

Just replace fields and it should works, it can be tested in a web browser and it should give the actual value in the device.

this code has mistakes
it takes only http not https for link
i spend a lot of time being a novice to understand the problem.

Thanks for notifying the issue.

i spend a lot of time being a novice to understand the problem.

And I’m very sorry to say that this will not be the last time until you become an expert and do not have the need to verify the publication of the best effort by free users in free forums and pages to solve your particular problem, so welcome to the real world :wink:

1 Like

Hola Ega. Gracias por compartir tu conocimiento.
No consigo ver el valor de payload por el monitor serie. Estoy seguro que estoy haciendo algo mal, soy bastante nuevo programando. Te dejo el código a ver si tienes un rato y puedes decirme que estoy haciendo mal.

#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <ThingerESP8266.h>

//Datos Thinger.io
#define USERNAME "EstacionMeteo"
#define DEVICE_ID "NodeMCU_Light"
#define DEVICE_CREDENTIAL "MYDEVICECREDENTIAL"
#define _DEBUG_

String link = "http://api.thinger.io/v1/users/EstacionMeteo/buckets/Prueba_bucket/data?items=1&max_ts=0&sort=desc&authorization=[MITOKEN]"; 
const char* ssid = "MIRED";
const char* ssid_PASSWORD = "MIPASSWORD";


HTTPClient http; //Cliente web

ThingerESP8266 thing(USERNAME, DEVICE_ID, DEVICE_CREDENTIAL);

void configWifi () {
#ifdef _DEBUG_
  //Conexión con la red wifi
  Serial.print ("Conectando con ");
  Serial.println (ssid);
#endif

  //Configuración en modo cliente
  WiFi.mode (WIFI_STA);
  //Iniciar conexión con la red wifi
  WiFi.begin (ssid, ssid_PASSWORD);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
#ifdef _DEBUG_
    Serial.print (".");
#endif
  }

#ifdef _DEBUG_
  Serial.println ("");
  Serial.print ("Conectado a la red ");
  Serial.println (ssid);
#endif
}

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
 Serial.println (httpCode);        //No muestra nada por el monitor serie
    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;
}

void setup() {
  Serial.begin (9600);
  configWifi();
  thing.add_wifi(ssid, ssid_PASSWORD);
 
}

void loop() {
 httpRequest (link);
  
}

Con este código debería ver el valor de payload por el monitor serie.
Igual que en el mensaje
How to take data from Api ans watch it in monitor serial in Arduino IDE? - How-To - The Internet of Thinger
que la respuesta obtenida con http.GET era -1 en el código que he pegado aquí, con
Serial.println (httpCode);
No muestra nada por el monitor serie.

¿Tienes idea que estoy haciendo mal?

Saludos!

Si abres un hilo con tu caso particular, continúa allí para conservar algo de orden con tu situación y en el foro.