Re: Using POST to add data points to a feed
by AlexanderMe on Sat Apr 10, 2021 3:25 pm
It turned out that it is perfectly possible to operate the AdafruitIO from Arduino using HTTP requests only.
Here are the relevant snippets (AdafruitIO credentials are #define(d) in IO_USERNAME and IO_KEY):
reading the latest value of a manual switch from a feed (this did not work if you device got disconnected or reset with the example AdafruitIO Arduino code)
void myGET(String feed) { // get last manual switch value from the dashboard
HTTPClient http;
//String serverPath = "http://io.adafruit.com/api/v2/<my_IO_USERNAME>/feeds/<myNameOfRequiredFeed>/data/last?X-AIO-Key=<my_IO_KEY>"; // replace <...> as appropriate
String serverPath = ((String)F("http://io.adafruit.com/api/v2/") + (String)IO_USERNAME + (String) F("/feeds/") + feed + (String) F("/data/last?X-AIO-Key=") + (String) IO_KEY);
http.begin(serverPath);
//http.addHeader("Content-Type", "application/json" , "Content-Length", jsonData.length()); //Specify content-type header (not required here)
uint32_t resp = http.GET();
String payload = http.getString();
if (resp != 200) {
Serial.println(resp);
Serial.println(payload);
}
// process the returned payload
int indVal = payload.indexOf("value")+8; // the JSON value is from indVal to "
if (payload.charAt(indVal) == '1')
is_on = 1;
else
is_on =0;
http.end();
}
adding new datum to a feed
void myPOST(String JSON_value, String feed) {
HTTPClient http;
String URL;
//String tst = "{\"value\":\"101.5\"}"; // example of a valid JSON string that needs to be passed on to myPOST; use tst to check validity for you
URL = ((String)"http://io.adafruit.com/api/v2/" + (String)IO_USERNAME + (String) "/feeds/" + feed + (String) "/data?X-AIO-Key=" + (String) IO_KEY);
http.begin(URL);
http.addHeader("Content-Type", "application/json" , "Content-Length", JSON_value.length()); //Specify content-type header (required)
int httpCode = http.POST(JSON_value); //Send the request
String payload = http.getString(); //Get the response payload
if (httpCode != 200) {
Serial.println(httpCode); //Print HTTP return code
Serial.println(payload); //Print request response payload
}
http.end(); //Close connection
}