2 * Copyright (c) 2010-2022 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 org.eclipse.jetty.http.HttpMethod.GET;
16 import static org.eclipse.jetty.http.HttpStatus.*;
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;
27 import java.util.concurrent.ExecutionException;
28 import java.util.concurrent.TimeUnit;
29 import java.util.concurrent.TimeoutException;
30 import java.util.stream.Collectors;
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.OpenWeatherMapOneCallAPIData;
44 import org.openhab.binding.openweathermap.internal.dto.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;
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;
63 * The {@link OpenWeatherMapConnection} is responsible for handling the connections to OpenWeatherMap API.
65 * @author Christoph Weitkamp - Initial contribution
68 public class OpenWeatherMapConnection {
70 private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapConnection.class);
72 private static final String PROPERTY_MESSAGE = "message";
74 private static final String PNG_CONTENT_TYPE = "image/png";
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";
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";
103 private final OpenWeatherMapAPIHandler handler;
104 private final HttpClient httpClient;
106 private static final ByteArrayFileCache IMAGE_CACHE = new ByteArrayFileCache("org.openhab.binding.openweathermap");
107 private final ExpiringCacheMap<String, String> cache;
109 private final Gson gson = new Gson();
111 public OpenWeatherMapConnection(OpenWeatherMapAPIHandler handler, HttpClient httpClient) {
112 this.handler = handler;
113 this.httpClient = httpClient;
115 OpenWeatherMapAPIConfiguration config = handler.getOpenWeatherMapAPIConfig();
116 cache = new ExpiringCacheMap<>(TimeUnit.MINUTES.toMillis(config.refreshInterval));
120 * Requests the current weather data for the given location (see https://openweathermap.org/current).
122 * @param location location represented as {@link PointType}
123 * @return the current weather data
124 * @throws JsonSyntaxException
125 * @throws CommunicationException
126 * @throws ConfigurationException
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);
137 * Requests the hourly forecast data for the given location (see https://openweathermap.org/forecast5).
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
146 public synchronized @Nullable OpenWeatherMapJsonHourlyForecastData getHourlyForecastData(
147 @Nullable PointType location, int count)
148 throws JsonSyntaxException, CommunicationException, ConfigurationException {
150 throw new ConfigurationException("@text/offline.conf-error-not-supported-number-of-hours");
153 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
154 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
156 return gson.fromJson(getResponseFromCache(buildURL(THREE_HOUR_FORECAST_URL, params)),
157 OpenWeatherMapJsonHourlyForecastData.class);
161 * Requests the daily forecast data for the given location (see https://openweathermap.org/forecast16).
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
170 public synchronized @Nullable OpenWeatherMapJsonDailyForecastData getDailyForecastData(@Nullable PointType location,
171 int count) throws JsonSyntaxException, CommunicationException, ConfigurationException {
173 throw new ConfigurationException("@text/offline.conf-error-not-supported-number-of-days");
176 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
177 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
179 return gson.fromJson(getResponseFromCache(buildURL(DAILY_FORECAST_URL, params)),
180 OpenWeatherMapJsonDailyForecastData.class);
184 * Requests the UV Index data for the given location (see https://openweathermap.org/api/uvi).
186 * @param location location represented as {@link PointType}
187 * @return the UV Index data
188 * @throws JsonSyntaxException
189 * @throws CommunicationException
190 * @throws ConfigurationException
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);
201 * Requests the UV Index forecast data for the given location (see https://openweathermap.org/api/uvi).
203 * @param location location represented as {@link PointType}
204 * @return the UV Index forecast data
205 * @throws JsonSyntaxException
206 * @throws CommunicationException
207 * @throws ConfigurationException
209 public synchronized @Nullable List<OpenWeatherMapJsonUVIndexData> getUVIndexForecastData(
210 @Nullable PointType location, int count)
211 throws JsonSyntaxException, CommunicationException, ConfigurationException {
213 throw new ConfigurationException("@text/offline.conf-error-not-supported-uvindex-number-of-days");
216 Map<String, String> params = getRequestParams(handler.getOpenWeatherMapAPIConfig(), location);
217 params.put(PARAM_FORECAST_CNT, Integer.toString(count));
219 return Arrays.asList(gson.fromJson(getResponseFromCache(buildURL(UVINDEX_FORECAST_URL, params)),
220 OpenWeatherMapJsonUVIndexData[].class));
224 * Requests the Air Pollution data for the given location (see https://openweathermap.org/api/air-pollution).
226 * @param location location represented as {@link PointType}
227 * @return the Air Pollution data
228 * @throws JsonSyntaxException
229 * @throws CommunicationException
230 * @throws ConfigurationException
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);
241 * Requests the Air Pollution forecast data for the given location (see
242 * https://openweathermap.org/api/air-pollution).
244 * @param location location represented as {@link PointType}
245 * @return the Air Pollution forecast data
246 * @throws JsonSyntaxException
247 * @throws CommunicationException
248 * @throws ConfigurationException
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);
259 * Downloads the icon for the given icon id (see https://openweathermap.org/weather-conditions).
261 * @param iconId the id of the icon
262 * @return the weather icon as {@link RawType}
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.");
269 return downloadWeatherIconFromCache(String.format(ICON_URL, iconId));
272 private static @Nullable RawType downloadWeatherIconFromCache(String url) {
273 if (IMAGE_CACHE.containsKey(url)) {
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);
281 RawType image = downloadWeatherIcon(url);
283 IMAGE_CACHE.put(url, image.getBytes());
290 private static @Nullable RawType downloadWeatherIcon(String url) {
291 return HttpUtil.downloadImage(url);
295 * Get Weather data from the One Call API for the given location. See https://openweathermap.org/api/one-call-api
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
303 * @throws JsonSyntaxException
304 * @throws CommunicationException
305 * @throws ConfigurationException
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");
316 exclude.add("hourly");
319 exclude.add("daily");
322 exclude.add("alerts");
324 logger.debug("Exclude: '{}'", exclude);
325 if (!exclude.isEmpty()) {
326 params.put(PARAM_EXCLUDE, exclude.stream().collect(Collectors.joining(",")));
328 return gson.fromJson(getResponseFromCache(buildURL(ONECALL_URL, params)), OpenWeatherMapOneCallAPIData.class);
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.
336 * @param location location represented as {@link PointType}
337 * @param days number of days in the past, relative to the current time.
339 * @throws JsonSyntaxException
340 * @throws CommunicationException
341 * @throws ConfigurationException
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);
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");
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");
364 params.put(PARAM_APPID, apikey);
366 // Units format (see https://openweathermap.org/current#data)
367 params.put(PARAM_UNITS, "metric");
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());
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());
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 + "?", ""));
386 private String encodeParam(@Nullable String value) {
387 return value == null ? "" : URLEncoder.encode(value, StandardCharsets.UTF_8);
390 private @Nullable String getResponseFromCache(String url) {
391 return cache.putIfAbsentAndGet(url, () -> getResponse(url));
394 private String getResponse(String url) {
396 if (logger.isTraceEnabled()) {
397 logger.trace("OpenWeatherMap request: URL = '{}'", uglifyApikey(url));
399 ContentResponse contentResponse = httpClient.newRequest(url).method(GET).timeout(10, TimeUnit.SECONDS)
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) {
408 case BAD_REQUEST_400:
409 case UNAUTHORIZED_401:
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)
417 errorMessage = getErrorMessage(content);
418 logger.debug("OpenWeatherMap server responded with status code {}: {}", httpStatus, errorMessage);
419 throw new CommunicationException(errorMessage);
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());
428 throw new CommunicationException(
429 errorMessage == null ? "@text/offline.communication-error" : errorMessage, e.getCause());
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,
439 private String uglifyApikey(String url) {
440 return url.replaceAll("(appid=)+\\w+", "appid=*****");
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();