Forum Sensor.Community

Link to sensor data for ESP32

I’ve got an airRohr sensor.

For my website i retrieve my data as follows…
$jsonurl = “http://data.sensor.community/airrohr/v1/sensor/”. $tempid."/";
$json = file_get_contents($jsonurl);
where $tempid is my sensorid. This works fine.

Now I want this data on my ESP32 too:

I used an existing example for weatherdata
// String serverPath = “http://api.openweathermap.org/data/2.5/weather?q=” + city + “,” + countryCode + “&APPID=” + openWeatherMapApiKey;

I received the json-file form openweather correctly.

So I changed the call to
String serverPath = “http://data.sensor.community/airrohr/v1/sensor/53656/”;

but now I receive an undocumented error:: HTTP Error code: -11

The call works correct when called in a browser.

So mine ESP32 can receive json-files, I can get a json-file with my sensor data from a browser and with my PHP-code.

I assume something wrong with the serverPath, but I can’t figure out what the error is,

I Check a code of mine soon.

There is another thing I discovered:
data.sensor.community changes to https even if you specify only http, when I retrieve my data from my browser Chrome of Firefox. ( is that correct for ‘open data’?)

maybe that the cause of my trouble. That should implicate that my site “veldbies.nl” is considered a trusted party, whereas my ESP8266 is not considered as a trusted party.

That should explain a lot.

Yes, I have just seen this:

static const char URL_API_SENSORCOMMUNITY[] PROGMEM = "https://data.sensor.community/airrohr/v1/sensor/";

then:

strcpy(url_ok, URL_API_SENSORCOMMUNITY);
strcat(url_ok, sensorNr);
strcat(url_ok, "/");

then:

float getData(const char *url, unsigned int pm_type)
{

  String pm="";

  switch (pm_type)
  {
  case 0:
    pm = "P0";
    break;
  case 1:
    pm = "P1";
    break;
  case 2:
    pm = "P2";
    break;
  }

  String reponseAPI;
  DynamicJsonDocument doc(JSON_BUFFER_SIZE);
  char reponseJSON[JSON_BUFFER_SIZE];
  if (!client.connect("data.sensor.community", httpPort))
  {
    Debug.println("connection failed");
    display.setSegments(oups);
    delay(1000);
    doc.garbageCollect();
    return -1.0;
  }

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + "data.sensor.community" + "\r\n" +
               "Connection: close\r\n\r\n");

  client.print(String("GET ") + url + " HTTP/1.1\r\n" +
               "Host: " + "data.sensor.community" + "\r\n" +
               "Connection: close\r\n\r\n");
  unsigned long timeout = millis();
  while (client.available() == 0)
  {
    if (millis() - timeout > 30000) //30s call to be sure the API answers
    {
      Debug.println("Client Timeout !");
      //client.flush();
      client.stop();
      display.setSegments(oups);
      delay(1000);
      doc.garbageCollect();
      return -1.0;
    }
  }
  // Read all the lines of the reply from server and print them to Serial
  while (client.available())
  {
    reponseAPI = client.readStringUntil('\r');
    strcpy(reponseJSON, reponseAPI.c_str());
    DeserializationError error = deserializeJson(doc, reponseJSON);
      if(strcmp (error.c_str(),"Ok") == 0) //revérifier
      {
        JsonArray JSONarray = doc.as<JsonArray>();
        serializeJsonPretty(doc, Debug);
        Debug.println("");
        JsonArray::iterator it = JSONarray.begin();
        JsonObject object = it->as<JsonObject>();
        JsonObject sensorAPI = object["sensor"].as<JsonObject>();
        serializeJsonPretty(sensorAPI, Debug);
        Debug.println("");
        for (JsonObject sensor : sensors_list)
        {
          if (sensorAPI["id"].as<String>() == sensor["sensor"])
          {
            sensor["time"] = object["timestamp"].as<String>();
            break;
          }
        }

        JsonArray dataarray = object["sensordatavalues"].as<JsonArray>();

        for (JsonObject dataobj : dataarray)
        {
          if (dataobj["value_type"].as<String>() == pm)
          {
            Debug.print("PM: ");
            Debug.println(dataobj["value"].as<String>());
            client.stop(); //OBLIGATOIRE?
            for (JsonObject sensor : sensors_list)
            {
              if (sensorAPI["id"].as<String>() == sensor["sensor"])
              {
                sensor["value"] = dataobj["value"].as<String>();
                break;
              }
            }
          //  client.flush();
          //  client.stop();
            doc.garbageCollect(); //empty buffer of JSONdocument
            //sensors_json.garbageCollect(); //empty buffer of JSONdocument
            return dataobj["value"].as<String>().toFloat();
          }
        }

        if (pm_type == 0)
        {
          display.setSegments(nop1);
          delay(1000);
          //client.flush();
         // client.stop();
          doc.garbageCollect();
          return -1.0;
        }
    }
    else
    {
      Debug.print(F("deserializeJson() failed: "));
      Debug.println(error.c_str());
    }
  }
  display.setSegments(oups);
  delay(1000);
  //client.flush();
  //client.stop();
  doc.garbageCollect();
  return -1.0;
}


But actually my code works on an NodeMCU 0.9.

That works perfectly in my PM Lamp.

The definition of open data is about the data itself, not about the way you get it … But beside this, I have checked the server configs and none of the data servers should redirect http to https.
Some browsers try to switch to the https version of a page if the server is answering on port 443. And they will also save the information that https is possible for a site if you called one time this way.

Thx for your reply and parts of your code.

Is it correct you use “https” and not “http” in your URL?

I didnt specify a httPort and you do, which port do you use?

As I understand from rick-z you can use “http” as well as “https” in the URL. May be I should use a specific port.

Yes, I programmed like this.

const int httpPort = 80;

I use these libraries as in the main firmware:

#include <ESP8266HTTPClient.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266mDNS.h>

This is part of the reply my ESP32 received:

Apache Server at srv02.sensor.community Port 80

Parsing input failed!
HTTP Response code: 400
jsonbuffer

400 Bad Request

Bad Request

Your browser sent a request that this server could not understand.
Reason: You're speaking plain HTTP to an SSL-enabled server port.
Instead use the HTTPS scheme to access this URL, please.

I used port 80 standard, but it seems you want me to speak HTTPS. At least that’s what it’s looks like.