2 * Copyright (c) 2010-2020 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.weathercompany.internal.handler;
15 import static org.openhab.binding.weathercompany.internal.WeatherCompanyBindingConstants.*;
17 import java.awt.image.BufferedImage;
18 import java.io.ByteArrayOutputStream;
20 import java.io.IOException;
21 import java.io.InputStream;
23 import java.util.Objects;
24 import java.util.concurrent.Future;
25 import java.util.concurrent.TimeUnit;
27 import javax.imageio.ImageIO;
29 import org.apache.commons.lang.StringUtils;
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.openhab.binding.weathercompany.internal.config.WeatherCompanyForecastConfig;
34 import org.openhab.binding.weathercompany.internal.model.DayPartDTO;
35 import org.openhab.binding.weathercompany.internal.model.ForecastDTO;
36 import org.openhab.core.i18n.LocaleProvider;
37 import org.openhab.core.i18n.TimeZoneProvider;
38 import org.openhab.core.i18n.UnitProvider;
39 import org.openhab.core.library.types.RawType;
40 import org.openhab.core.library.unit.Units;
41 import org.openhab.core.thing.ChannelUID;
42 import org.openhab.core.thing.Thing;
43 import org.openhab.core.thing.ThingStatus;
44 import org.openhab.core.thing.ThingStatusDetail;
45 import org.openhab.core.types.Command;
46 import org.openhab.core.types.RefreshType;
47 import org.openhab.core.types.State;
48 import org.openhab.core.types.UnDefType;
49 import org.osgi.framework.FrameworkUtil;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
53 import com.google.gson.JsonSyntaxException;
56 * The {@link WeatherCompanyForecastHandler} is responsible for pulling weather forecast
57 * information from the Weather Company API.
59 * API documentation is located here
60 * - https://docs.google.com/document/d/1eKCnKXI9xnoMGRRzOL1xPCBihNV2rOet08qpE_gArAY/edit
62 * @author Mark Hilbush - Initial contribution
65 public class WeatherCompanyForecastHandler extends WeatherCompanyAbstractHandler {
66 private static final String BASE_FORECAST_URL = "https://api.weather.com/v3/wx/forecast/daily/5day";
68 private final Logger logger = LoggerFactory.getLogger(WeatherCompanyForecastHandler.class);
70 private final LocaleProvider localeProvider;
72 private int refreshIntervalSeconds;
73 private String locationQueryString = "";
74 private String languageQueryString = "";
76 private @Nullable Future<?> refreshForecastJob;
78 private final Runnable refreshRunnable = new Runnable() {
85 public WeatherCompanyForecastHandler(Thing thing, TimeZoneProvider timeZoneProvider, HttpClient httpClient,
86 UnitProvider unitProvider, LocaleProvider localeProvider) {
87 super(thing, timeZoneProvider, httpClient, unitProvider);
88 this.localeProvider = localeProvider;
92 public void initialize() {
93 logger.debug("Forecast handler initializing with configuration: {}",
94 getConfigAs(WeatherCompanyForecastConfig.class).toString());
96 refreshIntervalSeconds = getConfigAs(WeatherCompanyForecastConfig.class).refreshInterval * 60;
97 if (isValidLocation()) {
98 weatherDataCache.clear();
100 scheduleRefreshJob();
101 updateStatus(isBridgeOnline() ? ThingStatus.ONLINE : ThingStatus.OFFLINE);
106 public void dispose() {
108 updateStatus(ThingStatus.OFFLINE);
112 public void handleCommand(ChannelUID channelUID, Command command) {
113 if (command.equals(RefreshType.REFRESH)) {
114 State state = weatherDataCache.get(channelUID.getId());
116 updateChannel(channelUID.getId(), state);
121 private boolean isValidLocation() {
122 boolean validLocation = false;
123 String locationType = getConfigAs(WeatherCompanyForecastConfig.class).locationType;
124 if (locationType == null) {
125 return validLocation;
127 switch (locationType) {
128 case CONFIG_LOCATION_TYPE_POSTAL_CODE:
129 String postalCode = StringUtils.trimToNull(getConfigAs(WeatherCompanyForecastConfig.class).postalCode);
130 if (postalCode == null) {
131 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Postal code is not set");
133 locationQueryString = "&postalKey=" + postalCode.replace(" ", "");
134 validLocation = true;
137 case CONFIG_LOCATION_TYPE_GEOCODE:
138 String geocode = StringUtils.trimToNull(getConfigAs(WeatherCompanyForecastConfig.class).geocode);
139 if (geocode == null) {
140 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Geocode is not set");
142 locationQueryString = "&geocode=" + geocode.replace(" ", "");
143 validLocation = true;
146 case CONFIG_LOCATION_TYPE_IATA_CODE:
147 String iataCode = StringUtils.trimToNull(getConfigAs(WeatherCompanyForecastConfig.class).iataCode);
148 if (iataCode == null) {
149 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "IATA code is not set");
151 locationQueryString = "&iataCode=" + iataCode.replace(" ", "").toUpperCase();
152 validLocation = true;
156 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Location Type is not set");
159 return validLocation;
162 private void setLanguage() {
163 String language = StringUtils.trimToNull(getConfigAs(WeatherCompanyForecastConfig.class).language);
164 if (language == null) {
165 // Nothing in the thing config, so try to get a match from the openHAB locale
166 String derivedLanguage = WeatherCompanyAbstractHandler.lookupLanguage(localeProvider.getLocale());
167 languageQueryString = "&language=" + derivedLanguage;
168 logger.debug("Language not set in thing config, using {}", derivedLanguage);
170 // Use what is set in the thing config
171 languageQueryString = "&language=" + language;
176 * Build the URL for requesting the 5-day forecast. It's important to request
177 * the desired language AND units so that the forecast narrative contains
178 * the consistent language and units (e.g. wind gusts to 30 mph).
180 private String buildForecastUrl() {
181 String apiKey = getApiKey();
182 StringBuilder sb = new StringBuilder(BASE_FORECAST_URL);
183 // Set response type as JSON
184 sb.append("?format=json");
185 // Set language from config
186 sb.append(languageQueryString);
187 // Set API key from config
188 sb.append("&apiKey=").append(apiKey);
189 // Set the units to Imperial or Metric
190 sb.append("&units=").append(getUnitsQueryString());
191 // Set the location from config
192 sb.append(locationQueryString);
193 String url = sb.toString();
194 logger.debug("Forecast URL is {}", url.replace(apiKey, REPLACE_API_KEY));
195 return url.toString();
198 private synchronized void refreshForecast() {
199 if (!isBridgeOnline()) {
200 // If bridge is not online, API has not been validated yet
201 logger.debug("Handler: Can't refresh forecast because bridge is not online");
204 logger.debug("Handler: Requesting forecast from The Weather Company API");
205 String response = executeApiRequest(buildForecastUrl());
206 if (response == null) {
210 logger.trace("Handler: Parsing forecast response: {}", response);
211 ForecastDTO forecast = Objects.requireNonNull(gson.fromJson(response, ForecastDTO.class));
212 logger.debug("Handler: Successfully parsed daily forecast response object");
213 updateStatus(ThingStatus.ONLINE);
214 updateDailyForecast(forecast);
215 updateDaypartForecast(forecast.daypart);
216 } catch (JsonSyntaxException e) {
217 logger.debug("Handler: Error parsing daily forecast response object", e);
218 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Error parsing daily forecast");
223 private void updateDailyForecast(ForecastDTO forecast) {
224 for (int day = 0; day < forecast.dayOfWeek.length; day++) {
225 logger.debug("Processing daily forecast for '{}'", forecast.dayOfWeek[day]);
226 updateDaily(day, CH_DAY_OF_WEEK, undefOrString(forecast.dayOfWeek[day]));
227 updateDaily(day, CH_NARRATIVE, undefOrString(forecast.narrative[day]));
228 updateDaily(day, CH_VALID_TIME_LOCAL, undefOrDate(forecast.validTimeUtc[day]));
229 updateDaily(day, CH_EXPIRATION_TIME_LOCAL, undefOrDate(forecast.expirationTimeUtc[day]));
230 updateDaily(day, CH_TEMP_MAX, undefOrQuantity(forecast.temperatureMax[day], getTempUnit()));
231 updateDaily(day, CH_TEMP_MIN, undefOrQuantity(forecast.temperatureMin[day], getTempUnit()));
232 updateDaily(day, CH_PRECIP_RAIN, undefOrQuantity(forecast.qpf[day], getLengthUnit()));
233 updateDaily(day, CH_PRECIP_SNOW, undefOrQuantity(forecast.qpfSnow[day], getLengthUnit()));
237 private void updateDaypartForecast(Object daypartObject) {
238 DayPartDTO[] dayparts;
240 String innerJson = gson.toJson(daypartObject);
241 logger.debug("Parsing daypartsObject: {}", innerJson);
242 dayparts = gson.fromJson(innerJson.toString(), DayPartDTO[].class);
243 logger.debug("Handler: Successfully parsed daypart forecast object");
244 } catch (JsonSyntaxException e) {
245 logger.debug("Handler: Error parsing daypart forecast object: {}", e.getMessage(), e);
246 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Error parsing daypart forecast");
249 logger.debug("There are {} daypart forecast entries", dayparts.length);
250 if (dayparts.length == 0) {
251 logger.debug("There is no daypart forecast object in this message");
254 logger.debug("There are {} daypartName entries in this forecast", dayparts[0].daypartName.length);
255 for (int i = 0; i < dayparts[0].daypartName.length; i++) {
256 // Note: All dayparts[0] (i.e. today day) values are null after 3 pm local time
257 DayPartDTO dp = dayparts[0];
258 // Even daypart indexes are Day (D); odd daypart indexes are Night (N)
259 String dOrN = dp.dayOrNight[i] == null ? (i % 2 == 0 ? "D" : "N") : dp.dayOrNight[i];
260 logger.debug("Processing daypart forecast for '{}'", dp.daypartName[i]);
261 updateDaypart(i, dOrN, CH_DP_NAME, undefOrString(dp.daypartName[i]));
262 updateDaypart(i, dOrN, CH_DP_DAY_OR_NIGHT, undefOrString(dayparts[0].dayOrNight[i]));
263 updateDaypart(i, dOrN, CH_DP_NARRATIVE, undefOrString(dayparts[0].narrative[i]));
264 updateDaypart(i, dOrN, CH_DP_WX_PHRASE_SHORT, undefOrString(dayparts[0].wxPhraseShort[i]));
265 updateDaypart(i, dOrN, CH_DP_WX_PHRASE_LONG, undefOrString(dayparts[0].wxPhraseLong[i]));
266 updateDaypart(i, dOrN, CH_DP_QUALIFIER_PHRASE, undefOrString(dayparts[0].qualifierPhrase[i]));
267 updateDaypart(i, dOrN, CH_DP_QUALIFIER_CODE, undefOrString(dayparts[0].qualifierCode[i]));
268 updateDaypart(i, dOrN, CH_DP_TEMP, undefOrQuantity(dp.temperature[i], getTempUnit()));
269 updateDaypart(i, dOrN, CH_DP_TEMP_HEAT_INDEX, undefOrQuantity(dp.temperatureHeatIndex[i], getTempUnit()));
270 updateDaypart(i, dOrN, CH_DP_TEMP_WIND_CHILL, undefOrQuantity(dp.temperatureWindChill[i], getTempUnit()));
271 updateDaypart(i, dOrN, CH_DP_HUMIDITY, undefOrQuantity(dp.relativeHumidity[i], Units.PERCENT));
272 updateDaypart(i, dOrN, CH_DP_CLOUD_COVER, undefOrQuantity(dp.cloudCover[i], Units.PERCENT));
273 updateDaypart(i, dOrN, CH_DP_PRECIP_CHANCE, undefOrQuantity(dp.precipChance[i], Units.PERCENT));
274 updateDaypart(i, dOrN, CH_DP_PRECIP_TYPE, undefOrString(dp.precipType[i]));
275 updateDaypart(i, dOrN, CH_DP_PRECIP_RAIN, undefOrQuantity(dp.qpf[i], getLengthUnit()));
276 updateDaypart(i, dOrN, CH_DP_PRECIP_SNOW, undefOrQuantity(dp.qpfSnow[i], getLengthUnit()));
277 updateDaypart(i, dOrN, CH_DP_SNOW_RANGE, undefOrString(dp.snowRange[i]));
278 updateDaypart(i, dOrN, CH_DP_WIND_SPEED, undefOrQuantity(dp.windSpeed[i], getSpeedUnit()));
279 updateDaypart(i, dOrN, CH_DP_WIND_DIR_CARDINAL, undefOrString(dp.windDirectionCardinal[i]));
280 updateDaypart(i, dOrN, CH_DP_WIND_PHRASE, undefOrString(dp.windPhrase[i]));
281 updateDaypart(i, dOrN, CH_DP_WIND_DIR, undefOrQuantity(dp.windDirection[i], Units.DEGREE_ANGLE));
282 updateDaypart(i, dOrN, CH_DP_THUNDER_CATEGORY, undefOrString(dp.thunderCategory[i]));
283 updateDaypart(i, dOrN, CH_DP_THUNDER_INDEX, undefOrDecimal(dp.thunderIndex[i]));
284 updateDaypart(i, dOrN, CH_DP_UV_DESCRIPTION, undefOrString(dp.uvDescription[i]));
285 updateDaypart(i, dOrN, CH_DP_UV_INDEX, undefOrDecimal(dp.uvIndex[i]));
286 updateDaypart(i, dOrN, CH_DP_ICON_CODE, undefOrDecimal(dp.iconCode[i]));
287 updateDaypart(i, dOrN, CH_DP_ICON_CODE_EXTEND, undefOrDecimal(dp.iconCodeExtend[i]));
288 updateDaypart(i, dOrN, CH_DP_ICON_IMAGE, getIconImage(dp.iconCode[i]));
292 private State getIconImage(Integer iconCode) {
293 // First try to get the image associated with the icon code
294 byte[] image = getImage("icons" + File.separator + String.format("%02d", iconCode) + ".png");
296 return new RawType(image, "image/png");
298 // Next try to get the N/A image
299 image = getImage("icons" + File.separator + "na.png");
301 return new RawType(image, "image/png");
303 // Couldn't get any icon image, so set to UNDEF
304 return UnDefType.UNDEF;
307 private byte @Nullable [] getImage(String iconPath) {
309 URL url = FrameworkUtil.getBundle(getClass()).getResource(iconPath);
310 logger.trace("Path to icon image resource is: {}", url);
312 try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
313 InputStream is = url.openStream();
314 BufferedImage image = ImageIO.read(is);
315 ImageIO.write(image, "png", out);
317 data = out.toByteArray();
318 } catch (IOException e) {
319 logger.debug("I/O exception occurred getting image data: {}", e.getMessage(), e);
325 private void updateDaily(int day, String channelId, State state) {
326 updateChannel(CH_GROUP_FORECAST_DAY + String.valueOf(day) + "#" + channelId, state);
329 private void updateDaypart(int daypartIndex, String dayOrNight, String channelId, State state) {
330 int day = daypartIndex / 2;
331 String dON = dayOrNight.equals("D") ? CH_GROUP_FORECAST_DAYPART_DAY : CH_GROUP_FORECAST_DAYPART_NIGHT;
332 updateChannel(CH_GROUP_FORECAST_DAY + String.valueOf(day) + dON + "#" + channelId, state);
336 * The refresh job updates the daily forecast on the
337 * refresh interval set in the thing config
339 private void scheduleRefreshJob() {
340 logger.debug("Handler: Scheduling forecast refresh job in {} seconds", REFRESH_JOB_INITIAL_DELAY_SECONDS);
342 refreshForecastJob = scheduler.scheduleWithFixedDelay(refreshRunnable, REFRESH_JOB_INITIAL_DELAY_SECONDS,
343 refreshIntervalSeconds, TimeUnit.SECONDS);
346 private void cancelRefreshJob() {
347 if (refreshForecastJob != null) {
348 refreshForecastJob.cancel(true);
349 logger.debug("Handler: Canceling forecast refresh job");