summaryrefslogtreecommitdiff
path: root/saltoqd/weathermanager.cpp
blob: 82126d736de93ee5179d61ca137b74f260ee4c56 (plain)
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
#include <QtCore/QFile>
#include <QtCore/QStandardPaths>
#include <QtCore/QJsonArray>
#include <QtGui/QPainter>

#include "fmsmanager.h"
#include "msolimageiohandler.h"
#include "weathermanager.h"

static QString getBackgroundImage(int temp)
{
	if (temp > 35) {
		return "temp40.png";
	} else if (temp > 25) {
		return "temp30.png";
	} else if (temp > 15) {
		return "temp20.png";
	} else if (temp > 5) {
		return "temp10.png";
	} else if (temp > -5) {
		return "temp0.png";
	} else if (temp > -15) {
		return "tempminus10.png";
	} else {
		return "tempminus20.png";
	}
}

WeatherManager::WeatherManager(FmsManager *fms, ToqManager *toq) :
	QObject(toq), _toq(toq), _fms(fms),
	_file(QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + "/sailfish-weather/weather.json"),
	_watcher(new QFileSystemWatcher(QStringList(_file), this)),
	_refreshTimer(new QTimer(this))
{
	connect(_watcher, &QFileSystemWatcher::fileChanged,
			_refreshTimer, static_cast<void (QTimer::*)()>(&QTimer::start));
	connect(_refreshTimer, &QTimer::timeout,
			this, &WeatherManager::doRefresh);

	qDebug() << "Monitoring file" << _file;

	_refreshTimer->setSingleShot(true);
	_refreshTimer->setInterval(2000);
	_refreshTimer->start();
}

QImage WeatherManager::constructImage(const QJsonObject &obj)
{
	QJsonObject weather = obj["weather"].toObject();
	QString city = obj["city"].toString();
	int temp = weather["temperatureFeel"].toInt();
	QImage img(RES_PATH "/card" + getBackgroundImage(temp));

	if (img.isNull()) {
		qWarning() << "Invalid background image" << QString(RES_PATH "/card" + getBackgroundImage(temp));
		return img;
	}

	QPainter p(&img);
	p.setPen(QColor(230, 230, 230));
	p.setFont(QFont("Qualcomm", 22));
	p.drawText(10, 36, city);

	p.setFont(QFont("Qualcomm", 48));
	p.drawText(14, 110, QString::fromUtf8("%1 °C").arg(temp));

	return img;
}

void WeatherManager::doRefresh()
{
	QFile file(_file);

	if (!file.open(QIODevice::ReadOnly)) {
		qWarning() << "Failed to open" << _file;
		return;
	}

	QJsonDocument doc = QJsonDocument::fromJson(file.readAll());
	QJsonObject root = doc.object();
	QJsonObject currentLoc = root["currentLocation"].toObject();
	QJsonArray locs = root["savedLocations"].toArray();

	int index = 1;
	QImage img = constructImage(currentLoc);
	_fms->updateFile(QString::fromLatin1("/apps/weather/%1.img").arg(index), convertImageToMsol(img));

	for (const QJsonValue &value : locs) {
		index++;
		img = constructImage(value.toObject());
		_fms->updateFile(QString::fromLatin1("/apps/weather/%1.img").arg(index), convertImageToMsol(img));
	}
}