Code for an ethernet-enabled mbed that calls to a web api, and reasons with JSON resonses

Dependencies:   NetServices RPCInterface mbed picojson xbee_api

main.cpp

Committer:
ammanvedi
Date:
2014-01-26
Revision:
3:2f263c4517e2
Parent:
2:86f64948da0f
Child:
4:fe02d3c20559

File content as of revision 3:2f263c4517e2:

#include "mbed.h"
#include "EthernetNetIf.h"
#include "HTTPClient.h"
#include "NTPClient.h"
#include "HTTPServer.h"
#include "RPCFunction.h"
#include <sstream>



#define HOSTNAME "HUB-01"
#define DEVICENAME "ADAM"



EthernetNetIf eth(HOSTNAME);
HTTPClient http;
NTPClient ntp;

using namespace std;

int main() {

   
    printf("Try starting the program with the network disconnected and then connect after a few timeouts reported\n\n");
    EthernetErr ethErr;
    int count = 0;
    do {
        printf("Setting up %d...\n", ++count);
        ethErr = eth.setup();
        if (ethErr) printf("Timeout\n", ethErr);
    } while (ethErr != ETH_OK);

    printf("Connected OK\n");
    const char* hwAddr = eth.getHwAddr();
    printf("HW address : %02x:%02x:%02x:%02x:%02x:%02x\n",
           hwAddr[0], hwAddr[1], hwAddr[2],
           hwAddr[3], hwAddr[4], hwAddr[5]);

    IpAddr ethIp = eth.getIp();
    printf("IP address : %d.%d.%d.%d\n", ethIp[0], ethIp[1], ethIp[2], ethIp[3]);
    
    char ip_buffer[20];
    sprintf(ip_buffer, "%d.%d.%d.%d", ethIp[0], ethIp[1], ethIp[2], ethIp[3]);
    
    //the hub will register itself with the server
     HTTPMap msg;
     
     stringstream url;
     url << "192.168.0.4:3000/hubconnect?h_id=" << HOSTNAME << "&h_name=" << DEVICENAME << "&h_ip=" << ip_buffer;
     const std::string uri = url.str();
     
     printf("query server : %s \n", uri);
  
   HTTPResult r1 = http.post(uri.c_str(),msg,NULL); 
  if( r1 == HTTP_OK )
  {
    printf("Hub %s registered with server (code : %d )\n", HOSTNAME, r1);
  }
  else
  {
    printf("Could not register, error : %d\n", r1);
  }
  
 
  

    printf("\nHTTPClient get...\n");
    HTTPText txt;
    HTTPResult r = http.get("192.168.0.4:3000/devices", &txt);
    if (r==HTTP_OK) {
        printf("Result ok : %s (code : %d )\n", txt.gets(), r);
    } else {
        printf("Error %s\n", txt.gets());
    }


}