Demonstrates the use of the spxml library to read and parse streamed XML (via HTTP). It calls out to the google weather API, parses the resulting XML and prints out the current temperature (for Los Angeles). It makes use of the HTTPClient library.
main.cpp
00001 #include "mbed.h" 00002 00003 #include "EthernetNetIf.h" 00004 #include "HTTPClient.h" 00005 00006 #include "spdomparser.hpp" 00007 #include "spxmlnode.hpp" 00008 #include "spxmlhandle.hpp" 00009 00010 EthernetNetIf eth; 00011 HTTPClient http; 00012 00013 HTTPResult result; 00014 bool completed = false; 00015 void request_callback(HTTPResult r) { 00016 result = r; 00017 completed = true; 00018 } 00019 00020 void parseWeather(SP_XmlElementNode *node) { 00021 SP_XmlHandle handle(node); 00022 SP_XmlElementNode * tempc = handle.getChild( "temp_c" ).toElement(); 00023 if (tempc) { 00024 printf("current temp=%sC\n",tempc->getAttrValue("data")); 00025 } 00026 SP_XmlElementNode * tempf = handle.getChild( "temp_f" ).toElement(); 00027 if (tempf) { 00028 printf("current temp=%sF\n",tempf->getAttrValue("data")); 00029 } 00030 } 00031 00032 int main() { 00033 // the eth and HTTP code has be taken directly from the HTTPStream documentation page 00034 // see http://mbed.org/cookbook/HTTP-Client-Data-Containers 00035 00036 printf("setup\n"); 00037 EthernetErr ethErr = eth.setup(); 00038 if (ethErr) { 00039 printf("Error in setup\n"); 00040 return -1; 00041 } 00042 printf("setup ok\n"); 00043 00044 SP_XmlDomParser parser; 00045 00046 HTTPStream stream; 00047 00048 char BigBuf[512 + 1] = {0}; 00049 stream.readNext((byte*)BigBuf, 512); //Point to buffer for the first read 00050 00051 HTTPResult r = http.get("http://www.google.com/ig/api?weather=Los+Angeles", &stream, request_callback); 00052 00053 while (!completed) { 00054 Net::poll(); //Polls the Networking stack 00055 if (stream.readable()) { 00056 BigBuf[stream.readLen()] = 0; //Transform this buffer in a zero-terminated char* string 00057 00058 parser.append( BigBuf, strlen(BigBuf)); // stream current buffer data to the XML parser 00059 00060 stream.readNext((byte*)BigBuf, 512); //Buffer has been read, now we can put more data in it 00061 } 00062 } 00063 if (result == HTTP_OK) { 00064 printf("Read completely\n"); 00065 } else { 00066 printf("Error %d\n", result); 00067 return -1; 00068 } 00069 00070 SP_XmlHandle rootHandle( parser.getDocument()->getRootElement() ); 00071 SP_XmlElementNode * child2 = rootHandle.getChild( "weather" ) 00072 .getChild( "current_conditions").toElement(); 00073 00074 if ( child2 ) { 00075 parseWeather(child2); 00076 } 00077 00078 if ( NULL != parser.getError() ) { 00079 printf( "\n\nerror: %s\n", parser.getError() ); 00080 } 00081 00082 printf("end\n"); 00083 00084 }
Generated on Wed Jul 20 2022 07:11:19 by 1.7.2