Pachube feed API/v2 by json

Dependencies:   NetServices mbed

main.cpp

Committer:
takashikojo
Date:
2011-11-13
Revision:
0:9b8c657f003c

File content as of revision 0:9b8c657f003c:

// includes

#include "mbed.h"
#include "EthernetNetIf.h"
#include "HTTPClient.h"

EthernetNetIf eth;
HTTPClient http;

// feed with 2 streams
char contentTemplate[] =  "{ \
  \"title\":\"TITLE HERE\", \"version\":\"1.0.0\",\
  \"datastreams\":[\
    { \"id\":\"STREAM ID\", \"current_value\":\"%d\"},\
    { \"id\":\"STREAM ID\", \"current_value\":\"%d\"}\
  ]\
}" ;

char content[200] ;

int main() {

    HTTPText txt;
    int r ;

    printf("Start\n");
    printf("\r\nSetting up...\r\n");
    EthernetErr ethErr = eth.setup();
    if (ethErr) {
        printf("Error %d in setup.\n", ethErr);
        return -1;
    }
    printf("\r\nSetup OK\r\n");

    // copy API key from settings
    string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

    // use feed ID
    string environmentID = "xxxxx";

    // for authentication, API key is set in client header
    HTTPClient client;
    client.setRequestHeader("X-PachubeApiKey", apiKey);

    // text object holds data to be posted
    HTTPText jsonContent("text/json");
    
    while (1) {
    
        sprintf(content, contentTemplate, rand()%40, rand()%100) ;
        printf("Json: %s\n", content) ;
        jsonContent.set(content) ;

        // uri for post includes feed ID
        string uri = "http://api.pachube.com/v2/feeds/" + environmentID + ".json?_method=put";

        // result should be 0 and response should be 200 for successful post
        HTTPResult result = client.post(uri.c_str(), jsonContent, NULL);

        if (result==HTTP_OK) {
            printf("Result :\"%s\"\n", txt.gets());
        } else {
            printf("Error %d\n", result);
        }


        r = client.getHTTPResponseCode();
        if (result==HTTP_OK) {
            printf("Result :\"%d\"\n", r);
        } else {
            printf("Error %d\n", r);
        }
        
        // wait for 60sec.
        wait(xx) ;
    }
}