Library for writing and reading on ThingSpeak with ethernet
ThingSpeak.cpp
- Committer:
- mpuric
- Date:
- 2017-06-28
- Revision:
- 2:5191c0e163d6
- Parent:
- 1:ea7f0ef29ef5
File content as of revision 2:5191c0e163d6:
#include "mbed.h"
#include "EthernetNetIf.h"
#include "HTTPClient.h"
#include "ThingSpeak.h"
Serial pc(USBTX, USBRX);
ThingSpeak::ThingSpeak(char* Key) : thingSpeakKey(Key) {
thingSpeakUrl = "https://api.thingspeak.com/update";
thingSpeakRead = "https://api.thingspeak.com/channels/";
urlBuffer[0] = 0;
fieldBuffer[0] = 0;
}
float ThingSpeak::pull(long int readKey, int field) {
sprintf(urlBuffer, "%s%d/fields/%d/last", thingSpeakRead, readKey, field );
pc.printf("URL Buffer request: %s ", urlBuffer);
res = http.get(urlBuffer, &resp);
if (res == HTTP_OK){
pc.printf(" Result :\"%s\"\r\n,", resp.gets(), res);
float resp2 = atoi(resp.gets());
return resp2;
}
else {
pc.printf(" Error %d\r\n", res);
return false;
}
}
void ThingSpeak::connect() {
pc.printf("Setting up Ethernet...\r\n");
EthernetErr ethErr = eth.setup();
if(ethErr){
pc.printf("Error %d in ethernet setup.\r\n", ethErr);
connect();
}
pc.printf("Ethernet setup OK\r\n");
}
void ThingSpeak::setField(float field, int i) {
char fieldi;
char fieldShortBuff[8];
sprintf(fieldShortBuff, "%f", field);
sprintf(&fieldi, "%i", i);
strncat(fieldBuffer, "&field", 6 );
strncat(fieldBuffer, &fieldi , 1);
strncat(fieldBuffer, "=", 1);
strncat(fieldBuffer, fieldShortBuff , 6);
}
void ThingSpeak::putUp() {
sprintf(urlBuffer, "%s?key=%s%s", thingSpeakUrl, thingSpeakKey, fieldBuffer);
pc.printf("URL Buffer request: %s ", urlBuffer);
res = http.get(urlBuffer, &resp);
if (res == HTTP_OK)
pc.printf(" Result :\"%s\"\r\n", resp.gets());
else
pc.printf(" Error %d\r\n", res);
fieldBuffer[0] = 0;
}