summaryrefslogtreecommitdiff
path: root/libforecastio/forecastio.c
blob: 83b9df92b06081c6f4043977afb2516afee26050 (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
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
#include <vdr/plugin.h>
#include <string>
#include <sstream>
#include <jansson.h>
#include "../config.h"
#include "../tools/curlfuncs.h"
#include "../tools/filesystem.h"
#include "forecastio.h"

using namespace std;
extern cWeatherforecastConfig weatherConfig;

cForecastIO::cForecastIO(string cacheDir) {
    forecastFile = *cString::sprintf("%s/%s", cacheDir.c_str(), "weather.json");
    cacheDurationDefault = 60 * 60 * weatherConfig.hoursToUpdate;
    apiKey = "9830052ef63efbec84ec0639e9a205d2";
    string osdLanguage = Setup.OSDLanguage;
    language = osdLanguage.substr(0,2);
    unit = "si";
    baseURL = "https://api.forecast.io/forecast";
    latitude = weatherConfig.lat;
    longitude = weatherConfig.lon;
    current = NULL;
    hourly = NULL;
    daily = NULL;
}

cForecastIO::~cForecastIO() {
    Clear();
}

/*****************************************************************
* PUBLIC FUNCTIONS
*****************************************************************/
void cForecastIO::Action(void) {
    loopActive = true;
    ReadForecastInitial();
    waitMutex.Lock();
    while (loopActive && Running()) {
        waitCondition.TimedWait(waitMutex, 1000 * 60);
        if (!loopActive)
            return;
        if (!CacheFileValid()) {
            ReadForecast();
        } 
    }
}

void cForecastIO::Stop() { 
    loopActive = false;
    waitCondition.Broadcast();
    Cancel(1);
    while (Active())
        cCondWait::SleepMs(10);
}

cForecast *cForecastIO::GetCurrentForecast(void) {
    time_t now = time(0);
    if (current && current->TimeMatch(now)) {
        return current;
    }
    if (hourly) {
        return hourly->GetCurrent();
    }
    return NULL;
}

bool cForecastIO::SetCurrentWeather(cServiceCurrentWeather *call) {
    cForecast *currentForecast = GetCurrentForecast();
    if (!currentForecast)
        return false;

    call->timeStamp = currentForecast->GetDateTimeString();
    call->temperature = currentForecast->GetTemperatureString();
    call->apparentTemperature = currentForecast->GetApparentTemperatureString();
    call->summary = currentForecast->GetSummary();
    call->icon = currentForecast->GetIcon();
    call->precipitationIntensity = currentForecast->GetPrecipIntensityString();
    call->precipitationProbability = currentForecast->GetPrecipProbabilityPercent();
    call->precipitationType = currentForecast->GetPercipType();
    call->humidity = currentForecast->GetHumidityPercent();
    call->windSpeed = currentForecast->GetWindSpeedString();
    call->windBearing = currentForecast->GetWindBearing();
    call->windBearingString = currentForecast->GetWindBearingString();
    call->visibility = currentForecast->GetVisibilityString();
    call->cloudCover = currentForecast->GetCloudCoverPercent();
    call->pressure = currentForecast->GetPressureString();
    call->ozone = currentForecast->GetOzoneString();

    cForecast *dailyForecast = daily->GetFirstDaily();
    if (!dailyForecast)
        return true;

    call->minTemperature = dailyForecast->GetTemperatureMinString();
    call->maxTemperature = dailyForecast->GetTemperatureMaxString();

    return true;
}

/*****************************************************************
* PRIVATE FUNCTIONS
*****************************************************************/

void cForecastIO::Clear(void) {
    if (current) {
        delete current;
        current = NULL;
    }
    if (hourly) {
        delete hourly;
        hourly = NULL;
    }
    if (daily) {
        delete daily;
        daily = NULL;
    }
}

bool cForecastIO::CheckUserApiKey(void) {
    if (weatherConfig.userApiKey.size() == 0)
        return false;
    if (weatherConfig.userApiKey.compare(apiKey) == 0) {
        return false;
    }
    return true;
}

int cForecastIO::CalculateCachDuration(void) {
    if (!CheckUserApiKey())
        return cacheDurationDefault;
    if (weatherConfig.userHoursToUpdate > 0 && weatherConfig.userHoursToUpdate <= 24) {
        return weatherConfig.userHoursToUpdate * 60 * 60;
    }
    return cacheDurationDefault;    
}

bool cForecastIO::CacheFileValid(void) {
    if (!FileExists(forecastFile)) {
        dsyslog("weatherforecast: no cached forecast available");
        return false;
    }
    int cacheDuration = CalculateCachDuration();
    time_t fileCreation = FileCreationTime(forecastFile);
    time_t now = time(0);
    int age = now - fileCreation;
    int ageHours = age / 3600;
    int ageMinutes = (age%3600) / 60;
    if (age > cacheDuration) {
        dsyslog("weatherforecast: cached forecast is outdated (age %dh %dmin, cache duration %dh)", ageHours, ageMinutes, cacheDuration / 3600);
        return false;
    }
    return true;
}

void cForecastIO::ReadForecastInitial(void) {
    string forecastJson = "";
    if (!CacheFileValid()) {
        //get new from forecast.io
        dsyslog("weatherforecast: fetching forecast newly from forecast.io");
        forecastJson = FetchOnlineForecast();
        WriteIntoFile(forecastFile, forecastJson);
    } else {
        //using cached data
        dsyslog("weatherforecast: using cached forecast");
        forecastJson = ReadFromFile(forecastFile);
    }
    ParseForecast(forecastJson);

}

void cForecastIO::ReadForecast(void) {
    dsyslog("weatherforecast: updating forecast from forecast.io");
    string forecastJson = "";
    forecastJson = FetchOnlineForecast();
    if (forecastJson.size() > 0) {
        WriteIntoFile(forecastFile, forecastJson);
        Lock();
        Clear();
        ParseForecast(forecastJson);
        Unlock();
    }
}

string cForecastIO::FetchOnlineForecast(void) {
    string myApiKey = apiKey;
    if (CheckUserApiKey())
        myApiKey = weatherConfig.userApiKey;
    stringstream url;
    url << baseURL << "/" << myApiKey;
    url << "/" << latitude << "," << longitude;
    url << "?lang=" << language << "&units=" << unit;
    string outputForecastIO;
    esyslog("weatherforecast: calling URL %s", url.str().c_str());
    CurlGetUrl(url.str().c_str(), &outputForecastIO);
    return outputForecastIO;
}

bool cForecastIO::ParseForecast(string &jsonForecast) {
    json_t *root;
    json_error_t error;

    root = json_loads(jsonForecast.c_str(), 0, &error);
    if ( !root ) {
        return false;
    }
    if ( !json_is_object(root) ) {
        return false;
    }

    //reading current weather
    json_t *currentWeather = json_object_get(root, "currently");
    if (!json_is_object(currentWeather)) {
        return false;
    }
    current = new cForecast();
    current->SetForecastType(ftCurrent);
    current->SetForecast(currentWeather);
    //current->Debug();

    //reading 48 hour forecast
    json_t *hourlyWeather = json_object_get(root, "hourly");
    if (!json_is_object(hourlyWeather)) {
        return false;
    }
    hourly = new cForecasts();
    hourly->SetForecastType(ftHourly);
    hourly->SetForecast(hourlyWeather);
    //hourly->Debug();

    //reading 7 day forecast
    json_t *dailyWeather = json_object_get(root, "daily");
    if (!json_is_object(dailyWeather)) {
        return false;
    }
    daily = new cForecasts();
    daily->SetForecastType(ftDaily);
    daily->SetForecast(dailyWeather);
    //daily->Debug();

    return true;
}