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