Pachube feed API/v2 by json

Dependencies:   NetServices mbed

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 // includes
00002 
00003 #include "mbed.h"
00004 #include "EthernetNetIf.h"
00005 #include "HTTPClient.h"
00006 
00007 EthernetNetIf eth;
00008 HTTPClient http;
00009 
00010 // feed with 2 streams
00011 char contentTemplate[] =  "{ \
00012   \"title\":\"TITLE HERE\", \"version\":\"1.0.0\",\
00013   \"datastreams\":[\
00014     { \"id\":\"STREAM ID\", \"current_value\":\"%d\"},\
00015     { \"id\":\"STREAM ID\", \"current_value\":\"%d\"}\
00016   ]\
00017 }" ;
00018 
00019 char content[200] ;
00020 
00021 int main() {
00022 
00023     HTTPText txt;
00024     int r ;
00025 
00026     printf("Start\n");
00027     printf("\r\nSetting up...\r\n");
00028     EthernetErr ethErr = eth.setup();
00029     if (ethErr) {
00030         printf("Error %d in setup.\n", ethErr);
00031         return -1;
00032     }
00033     printf("\r\nSetup OK\r\n");
00034 
00035     // copy API key from settings
00036     string apiKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
00037 
00038     // use feed ID
00039     string environmentID = "xxxxx";
00040 
00041     // for authentication, API key is set in client header
00042     HTTPClient client;
00043     client.setRequestHeader("X-PachubeApiKey", apiKey);
00044 
00045     // text object holds data to be posted
00046     HTTPText jsonContent("text/json");
00047     
00048     while (1) {
00049     
00050         sprintf(content, contentTemplate, rand()%40, rand()%100) ;
00051         printf("Json: %s\n", content) ;
00052         jsonContent.set(content) ;
00053 
00054         // uri for post includes feed ID
00055         string uri = "http://api.pachube.com/v2/feeds/" + environmentID + ".json?_method=put";
00056 
00057         // result should be 0 and response should be 200 for successful post
00058         HTTPResult result = client.post(uri.c_str(), jsonContent, NULL);
00059 
00060         if (result==HTTP_OK) {
00061             printf("Result :\"%s\"\n", txt.gets());
00062         } else {
00063             printf("Error %d\n", result);
00064         }
00065 
00066 
00067         r = client.getHTTPResponseCode();
00068         if (result==HTTP_OK) {
00069             printf("Result :\"%d\"\n", r);
00070         } else {
00071             printf("Error %d\n", r);
00072         }
00073         
00074         // wait for 60sec.
00075         wait(xx) ;
00076     }
00077 }