]> git.basschouten.com Git - openhab-addons.git/blob
a0bb9bcc871c2d6635fb6ca0811607cbb7458e9b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
7  * This program and the accompanying materials are made available under the
8  * terms of the Eclipse Public License 2.0 which is available at
9  * http://www.eclipse.org/legal/epl-2.0
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.openweathermap.internal.connection;
14
15 import static java.util.stream.Collectors.joining;
16 import static org.eclipse.jetty.http.HttpMethod.GET;
17 import static org.eclipse.jetty.http.HttpStatus.*;
18
19 import java.io.UnsupportedEncodingException;
20 import java.net.URLEncoder;
21 import java.nio.charset.StandardCharsets;
22 import java.time.ZoneId;
23 import java.time.ZonedDateTime;
24 import java.util.Arrays;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.TimeoutException;
31
32 import org.eclipse.jdt.annotation.NonNullByDefault;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.eclipse.jetty.client.HttpClient;
35 import org.eclipse.jetty.client.HttpResponseException;
36 import org.eclipse.jetty.client.api.ContentResponse;
37 import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapAPIConfiguration;
38 import org.openhab.binding.openweathermap.internal.dto.OpenWeatherMapJsonDailyForecastData;
39 import org.openhab.binding.openweathermap.internal.dto.OpenWeatherMapJsonHourlyForecastData;
40 import org.openhab.binding.openweathermap.internal.dto.OpenWeatherMapJsonUVIndexData;
41 import org.openhab.binding.openweathermap.internal.dto.OpenWeatherMapJsonWeatherData;
42 import org.openhab.binding.openweathermap.internal.dto.onecall.OpenWeatherMapOneCallAPIData;
43 import org.openhab.binding.openweathermap.internal.dto.onecallhist.OpenWeatherMapOneCallHistAPIData;
44 import org.openhab.binding.openweathermap.internal.handler.OpenWeatherMapAPIHandler;
45 import org.openhab.core.cache.ByteArrayFileCache;
46 import org.openhab.core.cache.ExpiringCacheMap;
47 import org.openhab.core.io.net.http.HttpUtil;
48 import org.openhab.core.library.types.PointType;
49 import org.openhab.core.library.types.RawType;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52
53 import com.google.gson.Gson;
54 import com.google.gson.JsonElement;
55 import com.google.gson.JsonObject;
56 import com.google.gson.JsonParser;
57 import com.google.gson.JsonSyntaxException;
58
59 /**
60  * The {@link OpenWeatherMapConnection} is responsible for handling the connections to OpenWeatherMap API.
61  *
62  * @author Christoph Weitkamp - Initial contribution
63  */
64 @NonNullByDefault
65 public class OpenWeatherMapConnection {
66
67     private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapConnection.class);
68
69     private static final String PROPERTY_MESSAGE = "message";
70
71     private static final String PNG_CONTENT_TYPE = "image/png";
72
73     private static final String PARAM_APPID = "appid";
74     private static final String PARAM_UNITS = "units";
75     private static final String PARAM_LAT = "lat";
76     private static final String PARAM_LON = "lon";
77     private static final String PARAM_LANG = "lang";
78     private static final String PARAM_FORECAST_CNT = "cnt";
79     private static final String PARAM_HISTORY_DATE = "dt";
80     private static final String PARAM_EXCLUDE = "exclude";
81
82     // Current weather data (see https://openweathermap.org/current)
83     private static final String WEATHER_URL = "https://api.openweathermap.org/data/2.5/weather";
84     // 5 day / 3 hour forecast (see https://openweathermap.org/forecast5)
85     private static final String THREE_HOUR_FORECAST_URL = "https://api.openweathermap.org/data/2.5/forecast";
86     // 16 day / daily forecast (see https://openweathermap.org/forecast16)
87     private static final String DAILY_FORECAST_URL = "https://api.openweathermap.org/data/2.5/forecast/daily";
88     // UV Index (see https://openweathermap.org/api/uvi)
89     private static final String UVINDEX_URL = "https://api.openweathermap.org/data/2.5/uvi";
90     private static final String UVINDEX_FORECAST_URL = "https://api.openweathermap.org/data/2.5/uvi/forecast";
91     // Weather icons (see https://openweathermap.org/weather-conditions)
92     private static final String ICON_URL = "https://openweathermap.org/img/w/%s.png";
93     // One Call API (see https://openweathermap.org/api/one-call-api )
94     private static final String ONECALL_URL = "https://api.openweathermap.org/data/2.5/onecall";
95     private static final String ONECALL_HISTORY_URL = "https://api.openweathermap.org/data/2.5/onecall/timemachine";
96
97     private final OpenWeatherMapAPIHandler handler;
98     private final HttpClient httpClient;
99
100     private static final ByteArrayFileCache IMAGE_CACHE = new ByteArrayFileCache("org.openhab.binding.openweathermap");
101     private final ExpiringCacheMap<String, String> cache;
102
103     private final Gson gson = new Gson();
104
105     public OpenWeatherMapConnection(OpenWeatherMapAPIHandler handler, HttpClient httpClient) {
106         this.handler = handler;
107         this.httpClient = httpClient;
108
109         OpenWeatherMapAPIConfiguration config = handler.getOpenWeatherMapAPIConfig();
110         cache = new ExpiringCacheMap<>(TimeUnit.MINUTES.toMillis(config.refreshInterval));
111     }
112
113     /**
114      * Requests the current weather data for the given location (see https://openweathermap.org/current).
115      *
116      * @param location location represented as {@link PointType}
117      * @return the current weather data
118      * @throws JsonSyntaxException
119      * @throws OpenWeatherMapCommunicationException
120      * @throws OpenWeatherMapConfigurationException
121      */
122     public synchronized @Nullable OpenWeatherMapJsonWeatherData getWeatherData(@Nullable PointType location)
123             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
124         return gson.fromJson(
125                 getResponseFromCache(
126                         buildURL(WEATHER_URL, getRequestParams(handler.getOpenWeatherMapAPIConfig(), location))),
127                 OpenWeatherMapJsonWeatherData.class);
128     }
129
130     /**
131      * Requests the hourly forecast data for the given location (see https://openweathermap.org/forecast5).
132      *
133      * @param location location represented as {@link PointType}
134      * @param count number of hours
135      * @return the hourly forecast data
136      * @throws JsonSyntaxException
137      * @throws OpenWeatherMapCommunicationException
138      * @throws OpenWeatherMapConfigurationException
139      */
140     public synchronized @Nullable OpenWeatherMapJsonHourlyForecastData getHourlyForecastData(
141             @Nullable PointType location, int count)
142             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
143         if (count <= 0) {
144             throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-not-supported-number-of-hours");
145         }
146
147         Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
148         params.put(PARAM_FORECAST_CNT, Integer.toString(count));
149
150         return gson.fromJson(getResponseFromCache(buildURL(THREE_HOUR_FORECAST_URL, params)),
151                 OpenWeatherMapJsonHourlyForecastData.class);
152     }
153
154     /**
155      * Requests the daily forecast data for the given location (see https://openweathermap.org/forecast16).
156      *
157      * @param location location represented as {@link PointType}
158      * @param count number of days
159      * @return the daily forecast data
160      * @throws JsonSyntaxException
161      * @throws OpenWeatherMapCommunicationException
162      * @throws OpenWeatherMapConfigurationException
163      */
164     public synchronized @Nullable OpenWeatherMapJsonDailyForecastData getDailyForecastData(@Nullable PointType location,
165             int count)
166             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
167         if (count <= 0) {
168             throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-not-supported-number-of-days");
169         }
170
171         Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
172         params.put(PARAM_FORECAST_CNT, Integer.toString(count));
173
174         return gson.fromJson(getResponseFromCache(buildURL(DAILY_FORECAST_URL, params)),
175                 OpenWeatherMapJsonDailyForecastData.class);
176     }
177
178     /**
179      * Requests the UV Index data for the given location (see https://api.openweathermap.org/data/2.5/uvi).
180      *
181      * @param location location represented as {@link PointType}
182      * @return the UV Index data
183      * @throws JsonSyntaxException
184      * @throws OpenWeatherMapCommunicationException
185      * @throws OpenWeatherMapConfigurationException
186      */
187     public synchronized @Nullable OpenWeatherMapJsonUVIndexData getUVIndexData(@Nullable PointType location)
188             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
189         return gson.fromJson(
190                 getResponseFromCache(
191                         buildURL(UVINDEX_URL, getRequestParams(handler.getOpenWeatherMapAPIConfig(), location))),
192                 OpenWeatherMapJsonUVIndexData.class);
193     }
194
195     /**
196      * Requests the UV Index forecast data for the given location (see https://api.openweathermap.org/data/2.5/uvi).
197      *
198      * @param location location represented as {@link PointType}
199      * @return the UV Index forecast data
200      * @throws JsonSyntaxException
201      * @throws OpenWeatherMapCommunicationException
202      * @throws OpenWeatherMapConfigurationException
203      */
204     public synchronized @Nullable List<OpenWeatherMapJsonUVIndexData> getUVIndexForecastData(
205             @Nullable PointType location, int count)
206             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
207         if (count <= 0) {
208             throw new OpenWeatherMapConfigurationException(
209                     "@text/offline.conf-error-not-supported-uvindex-number-of-days");
210         }
211
212         Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
213         params.put(PARAM_FORECAST_CNT, Integer.toString(count));
214
215         return Arrays.asList(gson.fromJson(getResponseFromCache(buildURL(UVINDEX_FORECAST_URL, params)),
216                 OpenWeatherMapJsonUVIndexData[].class));
217     }
218
219     /**
220      * Downloads the icon for the given icon id (see https://openweathermap.org/weather-conditions).
221      *
222      * @param iconId the id of the icon
223      * @return the weather icon as {@link RawType}
224      */
225     public static @Nullable RawType getWeatherIcon(String iconId) {
226         if (iconId.isEmpty()) {
227             throw new IllegalArgumentException("Cannot download weather icon as icon id is null.");
228         }
229
230         return downloadWeatherIconFromCache(String.format(ICON_URL, iconId));
231     }
232
233     private static @Nullable RawType downloadWeatherIconFromCache(String url) {
234         if (IMAGE_CACHE.containsKey(url)) {
235             try {
236                 return new RawType(IMAGE_CACHE.get(url), PNG_CONTENT_TYPE);
237             } catch (Exception e) {
238                 LoggerFactory.getLogger(OpenWeatherMapConnection.class)
239                         .trace("Failed to download the content of URL '{}'", url, e);
240             }
241         } else {
242             RawType image = downloadWeatherIcon(url);
243             if (image != null) {
244                 IMAGE_CACHE.put(url, image.getBytes());
245                 return image;
246             }
247         }
248         return null;
249     }
250
251     private static @Nullable RawType downloadWeatherIcon(String url) {
252         return HttpUtil.downloadImage(url);
253     }
254
255     /**
256      * Get Weather data from the OneCall API for the given location. See https://openweathermap.org/api/one-call-api for
257      * details
258      *
259      * @param location location represented as {@link PointType}
260      * @param excludeMinutely if true, will not fetch minutely forecast data from the server
261      * @param excludeHourly if true, will not fethh hourly forecast data from the server
262      * @param excludeDaily if true, will not fetch hourly forecast data from the server
263      * @return
264      * @throws JsonSyntaxException
265      * @throws OpenWeatherMapCommunicationException
266      * @throws OpenWeatherMapConfigurationException
267      */
268     public synchronized @Nullable OpenWeatherMapOneCallAPIData getOneCallAPIData(@Nullable PointType location,
269             boolean excludeMinutely, boolean excludeHourly, boolean excludeDaily)
270             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
271         Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
272         StringBuilder exclude = new StringBuilder("");
273         if (excludeMinutely) {
274             exclude.append("minutely");
275         }
276         if (excludeHourly) {
277             exclude.append(exclude.length() > 0 ? "," : "").append("hourly");
278         }
279         if (excludeDaily) {
280             exclude.append(exclude.length() > 0 ? "," : "").append("daily");
281         }
282         logger.debug("Exclude: '{}'", exclude);
283         if (exclude.length() > 0) {
284             params.put(PARAM_EXCLUDE, exclude.toString());
285         }
286         return gson.fromJson(getResponseFromCache(buildURL(ONECALL_URL, params)), OpenWeatherMapOneCallAPIData.class);
287     }
288
289     /**
290      * Get the historical weather data from the OneCall API for the given location and the given number of days in the
291      * past.
292      * As of now, OpenWeatherMap supports this function for up to 5 days in the past. However, this may change in the
293      * future,
294      * so we don't enforce this limit here. See https://openweathermap.org/api/one-call-api for details
295      *
296      * @param location location represented as {@link PointType}
297      * @param days number of days in the past, relative to the current time.
298      * @return
299      * @throws JsonSyntaxException
300      * @throws OpenWeatherMapCommunicationException
301      * @throws OpenWeatherMapConfigurationException
302      */
303     public synchronized @Nullable OpenWeatherMapOneCallHistAPIData getOneCallHistAPIData(@Nullable PointType location,
304             int days)
305             throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
306         Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
307         // the API requests the history as timestamp in Unix time format.
308         params.put(PARAM_HISTORY_DATE,
309                 Long.toString(ZonedDateTime.now(ZoneId.of("UTC")).minusDays(days).toEpochSecond()));
310         return gson.fromJson(getResponseFromCache(buildURL(ONECALL_HISTORY_URL, params)),
311                 OpenWeatherMapOneCallHistAPIData.class);
312     }
313
314     private Map<String, String> getRequestParams(OpenWeatherMapAPIConfiguration config, @Nullable PointType location) {
315         if (location == null) {
316             throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-missing-location");
317         }
318
319         Map<String, String> params = new HashMap<>();
320         // API key (see http://openweathermap.org/appid)
321         String apikey = config.apikey;
322         if (apikey == null || (apikey = apikey.trim()).isEmpty()) {
323             throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-missing-apikey");
324         }
325         params.put(PARAM_APPID, apikey);
326
327         // Units format (see https://openweathermap.org/current#data)
328         params.put(PARAM_UNITS, "metric");
329
330         // By geographic coordinates (see https://openweathermap.org/current#geo)
331         params.put(PARAM_LAT, location.getLatitude().toString());
332         params.put(PARAM_LON, location.getLongitude().toString());
333
334         // Multilingual support (see https://openweathermap.org/current#multi)
335         String language = config.language;
336         if (language != null && !(language = language.trim()).isEmpty()) {
337             params.put(PARAM_LANG, language.toLowerCase());
338         }
339         return params;
340     }
341
342     private String buildURL(String url, Map<String, String> requestParams) {
343         return requestParams.keySet().stream().map(key -> key + "=" + encodeParam(requestParams.get(key)))
344                 .collect(joining("&", url + "?", ""));
345     }
346
347     private String encodeParam(@Nullable String value) {
348         if (value == null) {
349             return "";
350         }
351         try {
352             return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
353         } catch (UnsupportedEncodingException e) {
354             logger.debug("UnsupportedEncodingException occurred during execution: {}", e.getLocalizedMessage(), e);
355             return "";
356         }
357     }
358
359     private @Nullable String getResponseFromCache(String url) {
360         return cache.putIfAbsentAndGet(url, () -> getResponse(url));
361     }
362
363     private String getResponse(String url) {
364         try {
365             if (logger.isTraceEnabled()) {
366                 logger.trace("OpenWeatherMap request: URL = '{}'", uglifyApikey(url));
367             }
368             ContentResponse contentResponse = httpClient.newRequest(url).method(GET).timeout(10, TimeUnit.SECONDS)
369                     .send();
370             int httpStatus = contentResponse.getStatus();
371             String content = contentResponse.getContentAsString();
372             String errorMessage = "";
373             logger.trace("OpenWeatherMap response: status = {}, content = '{}'", httpStatus, content);
374             switch (httpStatus) {
375                 case OK_200:
376                     return content;
377                 case BAD_REQUEST_400:
378                 case UNAUTHORIZED_401:
379                 case NOT_FOUND_404:
380                     errorMessage = getErrorMessage(content);
381                     logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage);
382                     throw new OpenWeatherMapConfigurationException(errorMessage);
383                 case TOO_MANY_REQUESTS_429:
384                     // TODO disable refresh job temporarily (see https://openweathermap.org/appid#Accesslimitation)
385                 default:
386                     errorMessage = getErrorMessage(content);
387                     logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage);
388                     throw new OpenWeatherMapCommunicationException(errorMessage);
389             }
390         } catch (ExecutionException e) {
391             String errorMessage = e.getLocalizedMessage();
392             logger.trace("Exception occurred during execution: {}", errorMessage, e);
393             if (e.getCause() instanceof HttpResponseException) {
394                 logger.debug("OpenWeatherMap server responded with status code {}: Invalid API key.", UNAUTHORIZED_401);
395                 throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-invalid-apikey", e.getCause());
396             } else {
397                 throw new OpenWeatherMapCommunicationException(errorMessage, e.getCause());
398             }
399         } catch (InterruptedException | TimeoutException e) {
400             logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
401             throw new OpenWeatherMapCommunicationException(e.getLocalizedMessage(), e.getCause());
402         }
403     }
404
405     private String uglifyApikey(String url) {
406         return url.replaceAll("(appid=)+\\w+", "appid=*****");
407     }
408
409     private String getErrorMessage(String response) {
410         JsonElement jsonResponse = JsonParser.parseString(response);
411         if (jsonResponse.isJsonObject()) {
412             JsonObject json = jsonResponse.getAsJsonObject();
413             if (json.has(PROPERTY_MESSAGE)) {
414                 return json.get(PROPERTY_MESSAGE).getAsString();
415             }
416         }
417         return response;
418     }
419 }