2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.openweathermap.internal.connection;
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.*;
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;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.TimeUnit;
30 import java.util.concurrent.TimeoutException;
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;
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;
60 * The {@link OpenWeatherMapConnection} is responsible for handling the connections to OpenWeatherMap API.
62 * @author Christoph Weitkamp - Initial contribution
65 public class OpenWeatherMapConnection {
67 private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapConnection.class);
69 private static final String PROPERTY_MESSAGE = "message";
71 private static final String PNG_CONTENT_TYPE = "image/png";
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";
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";
97 private final OpenWeatherMapAPIHandler handler;
98 private final HttpClient httpClient;
100 private static final ByteArrayFileCache IMAGE_CACHE = new ByteArrayFileCache("org.openhab.binding.openweathermap");
101 private final ExpiringCacheMap<String, String> cache;
103 private final Gson gson = new Gson();
105 public OpenWeatherMapConnection(OpenWeatherMapAPIHandler handler, HttpClient httpClient) {
106 this.handler = handler;
107 this.httpClient = httpClient;
109 OpenWeatherMapAPIConfiguration config = handler.getOpenWeatherMapAPIConfig();
110 cache = new ExpiringCacheMap<>(TimeUnit.MINUTES.toMillis(config.refreshInterval));
114 * Requests the current weather data for the given location (see https://openweathermap.org/current).
116 * @param location location represented as {@link PointType}
117 * @return the current weather data
118 * @throws JsonSyntaxException
119 * @throws OpenWeatherMapCommunicationException
120 * @throws OpenWeatherMapConfigurationException
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);
131 * Requests the hourly forecast data for the given location (see https://openweathermap.org/forecast5).
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
140 public synchronized @Nullable OpenWeatherMapJsonHourlyForecastData getHourlyForecastData(
141 @Nullable PointType location, int count)
142 throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
144 throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-not-supported-number-of-hours");
147 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
148 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
150 return gson.fromJson(getResponseFromCache(buildURL(THREE_HOUR_FORECAST_URL, params)),
151 OpenWeatherMapJsonHourlyForecastData.class);
155 * Requests the daily forecast data for the given location (see https://openweathermap.org/forecast16).
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
164 public synchronized @Nullable OpenWeatherMapJsonDailyForecastData getDailyForecastData(@Nullable PointType location,
166 throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
168 throw new OpenWeatherMapConfigurationException("@text/offline.conf-error-not-supported-number-of-days");
171 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
172 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
174 return gson.fromJson(getResponseFromCache(buildURL(DAILY_FORECAST_URL, params)),
175 OpenWeatherMapJsonDailyForecastData.class);
179 * Requests the UV Index data for the given location (see https://api.openweathermap.org/data/2.5/uvi).
181 * @param location location represented as {@link PointType}
182 * @return the UV Index data
183 * @throws JsonSyntaxException
184 * @throws OpenWeatherMapCommunicationException
185 * @throws OpenWeatherMapConfigurationException
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);
196 * Requests the UV Index forecast data for the given location (see https://api.openweathermap.org/data/2.5/uvi).
198 * @param location location represented as {@link PointType}
199 * @return the UV Index forecast data
200 * @throws JsonSyntaxException
201 * @throws OpenWeatherMapCommunicationException
202 * @throws OpenWeatherMapConfigurationException
204 public synchronized @Nullable List<OpenWeatherMapJsonUVIndexData> getUVIndexForecastData(
205 @Nullable PointType location, int count)
206 throws JsonSyntaxException, OpenWeatherMapCommunicationException, OpenWeatherMapConfigurationException {
208 throw new OpenWeatherMapConfigurationException(
209 "@text/offline.conf-error-not-supported-uvindex-number-of-days");
212 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
213 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
215 return Arrays.asList(gson.fromJson(getResponseFromCache(buildURL(UVINDEX_FORECAST_URL, params)),
216 OpenWeatherMapJsonUVIndexData[].class));
220 * Downloads the icon for the given icon id (see https://openweathermap.org/weather-conditions).
222 * @param iconId the id of the icon
223 * @return the weather icon as {@link RawType}
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.");
230 return downloadWeatherIconFromCache(String.format(ICON_URL, iconId));
233 private static @Nullable RawType downloadWeatherIconFromCache(String url) {
234 if (IMAGE_CACHE.containsKey(url)) {
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);
242 RawType image = downloadWeatherIcon(url);
244 IMAGE_CACHE.put(url, image.getBytes());
251 private static @Nullable RawType downloadWeatherIcon(String url) {
252 return HttpUtil.downloadImage(url);
256 * Get Weather data from the OneCall API for the given location. See https://openweathermap.org/api/one-call-api for
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
264 * @throws JsonSyntaxException
265 * @throws OpenWeatherMapCommunicationException
266 * @throws OpenWeatherMapConfigurationException
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");
277 exclude.append(exclude.length() > 0 ? "," : "").append("hourly");
280 exclude.append(exclude.length() > 0 ? "," : "").append("daily");
282 logger.debug("Exclude: '{}'", exclude);
283 if (exclude.length() > 0) {
284 params.put(PARAM_EXCLUDE, exclude.toString());
286 return gson.fromJson(getResponseFromCache(buildURL(ONECALL_URL, params)), OpenWeatherMapOneCallAPIData.class);
290 * Get the historical weather data from the OneCall API for the given location and the given number of days in the
292 * As of now, OpenWeatherMap supports this function for up to 5 days in the past. However, this may change in the
294 * so we don't enforce this limit here. See https://openweathermap.org/api/one-call-api for details
296 * @param location location represented as {@link PointType}
297 * @param days number of days in the past, relative to the current time.
299 * @throws JsonSyntaxException
300 * @throws OpenWeatherMapCommunicationException
301 * @throws OpenWeatherMapConfigurationException
303 public synchronized @Nullable OpenWeatherMapOneCallHistAPIData getOneCallHistAPIData(@Nullable PointType location,
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);
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");
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");
325 params.put(PARAM_APPID, apikey);
327 // Units format (see https://openweathermap.org/current#data)
328 params.put(PARAM_UNITS, "metric");
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());
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());
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 + "?", ""));
347 private String encodeParam(@Nullable String value) {
352 return URLEncoder.encode(value, StandardCharsets.UTF_8.name());
353 } catch (UnsupportedEncodingException e) {
354 logger.debug("UnsupportedEncodingException occurred during execution: {}", e.getLocalizedMessage(), e);
359 private @Nullable String getResponseFromCache(String url) {
360 return cache.putIfAbsentAndGet(url, () -> getResponse(url));
363 private String getResponse(String url) {
365 if (logger.isTraceEnabled()) {
366 logger.trace("OpenWeatherMap request: URL = '{}'", uglifyApikey(url));
368 ContentResponse contentResponse = httpClient.newRequest(url).method(GET).timeout(10, TimeUnit.SECONDS)
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) {
377 case BAD_REQUEST_400:
378 case UNAUTHORIZED_401:
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)
386 errorMessage = getErrorMessage(content);
387 logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage);
388 throw new OpenWeatherMapCommunicationException(errorMessage);
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());
397 throw new OpenWeatherMapCommunicationException(errorMessage, e.getCause());
399 } catch (InterruptedException | TimeoutException e) {
400 logger.debug("Exception occurred during execution: {}", e.getLocalizedMessage(), e);
401 throw new OpenWeatherMapCommunicationException(e.getLocalizedMessage(), e.getCause());
405 private String uglifyApikey(String url) {
406 return url.replaceAll("(appid=)+\\w+", "appid=*****");
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();