-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyrforecast.cpp
377 lines (342 loc) · 11.9 KB
/
yrforecast.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
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#include "yrforecast.h"
#include <iostream>
#include <QGeoAddress>
#include <QGeoCoordinate>
#include <QFile>
#include <QNetworkRequest>
#include <QDebug>
#include <QTextStream>
YrForecast::YrForecast(const QUrl &url, QNetworkAccessManager* manager, QObject *parent) : QObject(parent)
{
// Ensure minimum one forecast in the list
this->forecasts.append(new ForecastPoint());
// Setup download stuff
this->xmlUrl = url;
this->networkmanager = manager;
connect(this->networkmanager, &QNetworkAccessManager::finished,
this, &YrForecast::forecastDownloaded);
connect(this->networkmanager, &QNetworkAccessManager::finished,
this, &YrForecast::symbolDownloaded);
this->timer = new QTimer(this);
connect(this->timer, &QTimer::timeout,
this, &YrForecast::fetchForecast);
this->timer->setInterval(std::chrono::minutes(15));
}
YrForecast::~YrForecast()
{
qDeleteAll(this->forecasts);
this->forecasts.clear();
}
void YrForecast::startTimer()
{
this->fetchForecast();
this->timer->start();
}
void YrForecast::fetchForecast()
{
auto req = QNetworkRequest(this->xmlUrl);
this->networkmanager->get(req);
}
void YrForecast::forecastDownloaded(QNetworkReply* reply)
{
if (reply->url() == this->xmlUrl) {
auto err = reply->error();
if (err != QNetworkReply::NoError) {
qCritical() << "Failed downloading symbol:" << err;
}
this->readXml(reply->readAll());
reply->deleteLater();
}
}
bool YrForecast::readXmlFile(const QString &filename)
{
QFile f(filename);
if (!f.open(QFile::ReadOnly | QFile::Text)) {
qCritical() << "Cannot read file: " << f.errorString();
exit(1);
}
return this->readXml(f.readAll());
}
bool YrForecast::readXml(const QByteArray &xmlData)
{
qDeleteAll(this->forecasts);
this->forecasts.clear();
this->xml.addData(xmlData);
if (this->xml.readNextStartElement()) {
if (this->xml.name() != "weatherdata") {
this->xml.raiseError("Unexpected file format. Expected <weatherdata> start tag");
}
else {
this->readWeatherData();
}
}
if (this->xml.hasError()) {
qCritical() << "XML parse error: " << this->xml.errorString();
return false;
}
this->xml.clear();
auto current = this->current();
emit this->forecastUpdated(current->temperature(),
current->precipitation(),
current->time());
this->fetchSymbol(current->symbolUrl());
return true;
}
void YrForecast::readWeatherData()
{
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "location") {
this->readLocation();
} else if (name == "credit") {
this->readCredits();
} else if (name == "links") {
this->readLinks();
} else if (name == "meta") {
this->readMeta();
} else if (name == "sun") {
this->readSun();
} else if (name == "forecast") {
this->readForecast();
} else if (name == "weatherstation") {
this->readObservation();
}
}
}
void YrForecast::readLocation()
{
QGeoAddress address;
QGeoCoordinate coord;
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "name") {
address.setCity(this->xml.readElementText());
} else if (name == "type") {
this->xml.skipCurrentElement(); // Skipping
} else if (name == "country") {
address.setCountry(this->xml.readElementText());
} else if (name == "timezone") {
this->xml.skipCurrentElement(); // Skipping
} else if (name == "location") {
auto attrs = this->xml.attributes();
coord.setAltitude(attrs.value("altitude").toString().toDouble());
coord.setLatitude(attrs.value("latitude").toString().toDouble());
coord.setLongitude(attrs.value("longitude").toString().toDouble());
this->xml.skipCurrentElement();
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
this->xml.skipCurrentElement();
}
}
this->location.setAddress(address);
this->location.setCoordinate(coord);
}
void YrForecast::readCredits()
{
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "link") {
auto attrs = this->xml.attributes();
this->credit = attrs.value("text").toString();
this->creditUrl.setUrl(attrs.value("url").toString());
this->xml.skipCurrentElement();
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
this->xml.skipCurrentElement();
}
}
}
void YrForecast::readLinks()
{
qInfo() << "Skipping link data";
this->xml.skipCurrentElement();
}
void YrForecast::readMeta()
{
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "lastupdate") {
this->lastUpdate = QDateTime::fromString(xml.readElementText(), Qt::ISODate);
} else if (name == "nextupdate") {
this->nextUpdate= QDateTime::fromString(xml.readElementText(), Qt::ISODate);
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
this->xml.skipCurrentElement();
}
}
}
void YrForecast::readSun()
{
auto attrs = this->xml.attributes();
this->sunrise = QDateTime::fromString(attrs.value("rise").toString(), Qt::ISODate);
this->sunset = QDateTime::fromString(attrs.value("set").toString(), Qt::ISODate);
this->xml.skipCurrentElement();
}
void YrForecast::readForecast()
{
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "text") {
this->xml.skipCurrentElement();
} else if (name == "tabular") {
this->readForecastTabular();
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
qInfo() << "Skipping: " << name;
this->xml.skipCurrentElement();
}
}
}
void YrForecast::readObservation()
{
qInfo() << "Skipping weatherstation data";
this->xml.skipCurrentElement();
}
void YrForecast::readForecastTabular()
{
while (this->xml.readNextStartElement()) {
auto name = this->xml.name().toString();
if (name == "time") {
auto attrs = this->xml.attributes();
auto from = QDateTime::fromString(attrs.value("from").toString(), Qt::ISODate);
auto to = QDateTime::fromString(attrs.value("to").toString(), Qt::ISODate);
auto period = attrs.value("from").toInt();
ForecastPoint* point = new ForecastPoint(from, to, period);
point->readXml(&this->xml);
forecasts.append(point);
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
this->xml.skipCurrentElement();
}
}
}
ForecastPoint::ForecastPoint(const QDateTime &from, const QDateTime &to, int period): from(from), to(to), period(period) {}
ForecastPoint::ForecastPoint() {}
void ForecastPoint::readXml(QXmlStreamReader* xml)
{
while (xml->readNextStartElement()) {
auto name = xml->name().toString();
auto attrs = xml->attributes();
if (name == "symbol") {
// The SVG format used by Yr is not supported by Qt, which
// only supports SVG Tiny (1.2).
// // https://symbol.yr.no/grafikk/sym/svg/{var}.svg
// // Eg. https://symbol.yr.no/grafikk/sym/svg/34.svg (for var = '34')
// Using PNG instead
// https://www.yr.no/grafikk/sym/v2017/png/200/{var}.png
// (Deprecated? https://symbol.yr.no/grafikk/sym/b200/{var}.png)
this->condition = attrs.value("name").toString();
auto symId = attrs.value("var").toString();
this->symbol = QUrl(QString("https://www.yr.no/grafikk/sym/v2017/png/200/%1.png").arg(symId));
xml->skipCurrentElement();
} else if (name == "precipitation") {
this->precip= attrs.value("value").toDouble();
this->precipMin = attrs.value("minvalue").toDouble();
this->precipMax = attrs.value("maxvalue").toDouble();
xml->skipCurrentElement();
} else if (name == "windDirection") {
this->windDir= attrs.value("deg").toDouble();
xml->skipCurrentElement();
} else if (name == "windSpeed") {
this->_windSpeed = attrs.value("mps").toDouble();
xml->skipCurrentElement();
} else if (name == "temperature") {
this->temp= attrs.value("value").toDouble();
this->tempUnit = attrs.value("unit").toString();
xml->skipCurrentElement();
} else if (name == "pressure") {
this->_pressure = attrs.value("value").toDouble();
this->_pressureUnit = attrs.value("unit").toString();
xml->skipCurrentElement();
} else {
// Unknown tags. Should not really appear. Perhaps a warning?
xml->skipCurrentElement();
}
}
}
const QString YrForecast::toString() const
{
QString s;
QTextStream out(&s);
out << "Location: " << this->location.address().text() << endl;
out << "Coordinate: " << this->location.coordinate().toString() << endl;
out << "Credit: " << this->credit << endl;
out << "Credit URL: " << this->creditUrl.toString() << endl;
out << "Last update: " << this->lastUpdate.toString() << endl;
out << "Next update: " << this->nextUpdate.toString() << endl;
out << "Sunrise: " << this->sunrise.toString() << endl;
out << "Sunset: " << this->sunset.toString() << endl;
for (auto forecast : this->forecasts) {
out << forecast->toString();
}
return s;
}
void YrForecast::print()
{
std::cout << this->toString().toStdString();
}
ForecastPoint* YrForecast::current()
{
return forecasts.first();
}
void YrForecast::fetchSymbol(const QUrl &url)
{
qInfo() << "Fetching symbol: " << url.toString();
auto req = QNetworkRequest(url);
this->networkmanager->get(req);
}
void YrForecast::symbolDownloaded(QNetworkReply* reply)
{
auto url = reply->url();
if (url.host() == "www.yr.no" && url.path().startsWith("/grafikk/sym")) {
auto err = reply->error();
if (err != QNetworkReply::NoError) {
qCritical() << "Failed downloading symbol:" << err;
}
emit symbolUpdated(reply->readAll());
reply->deleteLater();
}
}
/////////////////////////////////////////
/// ForecastPoint stuff
/////////////////////////////////////////
const QString ForecastPoint::toString() const
{
QString s;
QTextStream out(&s);
out << from.toString() << " to " << to.toString() << " (" << period << "):" << endl;
out << condition << ", " << temp << " " << tempUnit << ", "
<< precip << " mm (" << precipMin << "-" << precipMax << " mm), "
<< _windSpeed << " m/s " << windDir<< " degrees, " << endl;
return s;
}
void ForecastPoint::print()
{
std::cout << this->toString().toStdString();
}
const QString ForecastPoint::temperature() const
{
QString unit;
if (this->tempUnit == "celsius") {
unit = "°C";
} else if (this->tempUnit == "fahrenheit") {
unit = "°F";
}
return QString("%1%2").arg(this->temp).arg(unit);
}
const QString ForecastPoint::precipitation() const
{
return QString("%1 - %2 mm").arg(this->precipMin).arg(this->precipMax);
}
const QString ForecastPoint::time() const
{
QString ret;
QTextStream s(&ret);
s << "" << this->from.toString(Qt::SystemLocaleShortDate) << endl
<< QString::fromUtf8("\u2192 ") << this->to.toString(Qt::SystemLocaleShortDate);
return ret;
}
const QUrl ForecastPoint::symbolUrl() const
{
return this->symbol;
}