Fork of my original MQTTGateway

Dependencies:   mbed-http

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers WeatherInfo.cpp Source File

WeatherInfo.cpp

00001 #include "WeatherInfo.h"
00002 #include <string.h>
00003 #include <stdlib.h>
00004 
00005 static int jsoneq(const char * json, jsmntok_t * tok, const char * s)
00006 {
00007     if (tok->type == JSMN_STRING && (int) strlen(s) == tok->end - tok->start &&
00008         strncmp(json + tok->start, s, tok->end - tok->start) == 0) {
00009             return 0;
00010     }
00011     return -1;    
00012 }
00013 
00014 int parseweatherinfo(const char * weather, WeatherInfo & winfo)
00015 {
00016     // Parse weather information
00017     jsmn_parser p;
00018     jsmntok_t t[128];
00019 
00020     jsmn_init(&p);
00021     int r = jsmn_parse(&p, weather, strlen(weather), t, sizeof(t)/sizeof(t[0]));
00022     // Top level must be an object
00023     if ((r > 0) && (t[0].type == JSMN_OBJECT)) 
00024     { 
00025         /* Loop over all keys of the root object */
00026         for (int i = 1; i < r; i++)
00027         {
00028             if (jsoneq(weather, &t[i], "description") == 0)
00029             {
00030                 winfo.weather = std::string((const char *)(weather + t[i+1].start), (size_t) t[i+1].end - t[i+1].start);
00031                 i++;
00032             }
00033             else if (jsoneq(weather, &t[i], "icon") == 0)
00034             {
00035                 winfo.icon = std::string((const char *)(weather + t[i+1].start), (size_t) t[i+1].end - t[i+1].start);
00036                 i++;
00037             }
00038             else if (jsoneq(weather, &t[i], "temp") == 0)
00039             {
00040                 std::string tempstr((const char *)(weather + t[i+1].start), (size_t) t[i+1].end - t[i+1].start);
00041                 winfo.temperature = strtod(tempstr.c_str(), NULL);
00042                 i++;
00043             }
00044             else if (jsoneq(weather, &t[i], "humidity") == 0)
00045             {
00046                 std::string humidstr((const char *)(weather + t[i+1].start), (size_t) t[i+1].end - t[i+1].start);
00047                 winfo.humidity = strtod(humidstr.c_str(), NULL);
00048                 i++;
00049             }            
00050             else if (jsoneq(weather, &t[i], "pressure") == 0)
00051             {
00052                 std::string pressurestr((const char *)(weather + t[i+1].start), (size_t) t[i+1].end - t[i+1].start);
00053                 winfo.pressure = strtod(pressurestr.c_str(), NULL);
00054                 i++;
00055             }else
00056             {
00057                 // discard the rest of the tokens
00058             }
00059         }
00060         return 0;
00061     }else
00062         return -1;
00063 }