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