-
Notifications
You must be signed in to change notification settings - Fork 1
/
weather.cpp
133 lines (112 loc) · 2.95 KB
/
weather.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
#include <QNetworkAccessManager>
#include <QThread>
#include "weather.h"
#include "dataanalyze.h"
Weather::Weather(bool moreMessage,QString place,QObject *parent) :
QObject(parent)
{
this->place = place;
this->moreMessage =moreMessage;
manager = new QNetworkAccessManager(this);
connect(manager,SIGNAL(finished(QNetworkReply*)),
this,SLOT(getCityInfo(QNetworkReply*)));
if(needImportCityID()){
fromFileToList();
CityID = findIdByCityName(place);
if(CityID.isEmpty()){
qDebug() << "未找到城市,请确定是否正确输入";
exit(1);
}
}
connect(this,SIGNAL(initSender()),this,SLOT(beginSender()));
}
void Weather::ImportCityID(QString cityName,QString id)
{
QPair<QString,QString> tempPair;
tempPair.first = cityName;
tempPair.second = id;
cityList.append(tempPair);
}
//将文件导入导QList<QPair<...>>之中
void Weather::fromFileToList()
{
QFile file(":/data/data/CityID");
if(!file.open(QIODevice::ReadOnly)){
qDebug() << "Get City ID Error\n"
<< file.errorString();
exit(1);
}
QTextStream textStream(&file);
QString line;
QStringList list;
do {
line = textStream.readLine();
list = line.split("=",QString::SkipEmptyParts);
if(!list.isEmpty()){
ImportCityID(list.at(0),list.at(1));
}
}while(!line.isNull());
file.close();
}
//得到本地的城市ID号
void Weather::getLocalCityID()
{
manager->get(QNetworkRequest(QUrl("http://61.4.185.48:81/g/")));
}
//通过城市名找到城市ID
QString Weather::findIdByCityName(QString cityName)
{
QPair<QString,QString> city;
foreach (city, cityList) {
if(city.second == cityName){
return city.first;
}
}
return NULL;
}
//获得天气数据
void Weather::getWeather()
{
if(CityID.isEmpty()){
getLocalCityID();
} else{
beginSender();
}
}
//得到服务器返回的本地城市ID
void Weather::getCityInfo(QNetworkReply *reply)
{
QByteArray byteArray = reply->readAll();
QString strScript(byteArray);
QStringList list = strScript.split(";");
if(list.count() > 2){
QStringList idList = list.at(1).split("=");
CityID = idList.at(1);
emit initSender();
}
}
void Weather::receiveData(QList<QByteArray> byteArray)
{
DataAnalyze *anlyze = new DataAnalyze(byteArray,moreMessage);
connect(anlyze,SIGNAL(finish()),this,SLOT(finish()));
anlyze->Analyse();
}
void Weather::finish()
{
emit getWeatherFinished();
}
void Weather::beginSender()
{
sender = new Sender(CityID);
connect(sender,SIGNAL(sendData(QList<QByteArray>)),
this,SLOT(receiveData(QList<QByteArray>)));
sender->Send();
}
//判断是否需要导入城市ID,如果是本地的话,就不需要
bool Weather::needImportCityID()
{
if(place.isEmpty())
return false;
else
return true;
}