86 lines
2.5 KiB
C++
86 lines
2.5 KiB
C++
#include "Weather.h"
|
|
#include "util.h"
|
|
#include "rapidxml/rapidxml.hpp"
|
|
#include "log.h"
|
|
using namespace std;
|
|
using namespace rapidxml;
|
|
|
|
using XNode = rapidxml::xml_node<>* ;
|
|
using XAttr = rapidxml::xml_attribute<>* ;
|
|
using XDoc = rapidxml::xml_document<> ;
|
|
|
|
Weather::Weather()
|
|
{
|
|
_status=-1;
|
|
}
|
|
|
|
bool Weather::isReady() const
|
|
{
|
|
return _status>=0;
|
|
}
|
|
|
|
/// static
|
|
Weather Weather::GetWeather(const std::string& CityName)
|
|
{
|
|
Weather w;
|
|
|
|
HTTPRequest req;
|
|
req.host="wthrcdn.etouch.cn";
|
|
req.url="/WeatherApi?city=";
|
|
req.url.append(CityName);
|
|
|
|
HTTPResponse res;
|
|
int ret=req.send(res);
|
|
|
|
dprintf("WeatherResponse: \n%s\n",res.content.c_str());
|
|
|
|
dprintf("Response Protocol: %s\n",res.protocol.c_str());
|
|
dprintf("Response Status: %d\n",res.status);
|
|
dprintf("Response Content Type: %s\n",res.content_type.c_str());
|
|
dprintf("Response Content Length: %d\n",res.content_length);
|
|
|
|
if(ret==0)
|
|
{
|
|
XDoc doc;
|
|
|
|
try {
|
|
doc.parse<0>(doc.allocate_string(res.content.c_str(),res.content.size()));
|
|
} catch (exception& e) {
|
|
dprintf("Failed to parse xml document. Exception: %s\n",e.what());
|
|
return w;
|
|
}
|
|
|
|
XNode beginNode=doc.first_node("resp");
|
|
|
|
#define WeatherReadFrom beginNode
|
|
#define WeatherReadInt(XMLNodeName,Target) sscanf(WeatherReadFrom->first_node(XMLNodeName)->value(),"%d",&(Target))
|
|
#define WeatherReadTime(XMLNodeName,Target) sscanf(WeatherReadFrom->first_node(XMLNodeName)->value(),"%d:%d",&(Target.h),&(Target.m))
|
|
WeatherReadInt("wendu",w.temperature);
|
|
WeatherReadInt("shidu",w.humidity);
|
|
WeatherReadTime("sunrise_1",w.sunrise);
|
|
WeatherReadTime("sunset_1",w.sunset);
|
|
|
|
XNode environNode=beginNode->first_node("environment");
|
|
#undef WeatherReadFrom
|
|
#define WeatherReadFrom environNode
|
|
WeatherReadInt("aqi",w.aqi);
|
|
WeatherReadInt("pm25",w.pm25);
|
|
WeatherReadInt("o3",w.o3);
|
|
WeatherReadInt("co",w.co);
|
|
WeatherReadInt("pm10",w.pm10);
|
|
WeatherReadInt("so2",w.so2);
|
|
WeatherReadInt("no2",w.no2);
|
|
|
|
#undef WeatherReadInt
|
|
#undef WeatherReadTime
|
|
#undef WeatherReadFrom
|
|
|
|
w.suggestion=string(environNode->first_node("suggest")->value(),environNode->first_node("suggest")->value_size());
|
|
w.quality=string(environNode->first_node("quality")->value(),environNode->first_node("quality")->value_size());
|
|
|
|
w._status=1;
|
|
}
|
|
|
|
return w;
|
|
}
|