]> git.basschouten.com Git - openhab-addons.git/blob
fc2c7983e0a70af1a6a7e574c3119ca2b9cf85ac
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.weathercompany.internal.handler;
14
15 import static org.openhab.binding.weathercompany.internal.WeatherCompanyBindingConstants.*;
16
17 import java.awt.image.BufferedImage;
18 import java.io.ByteArrayOutputStream;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22 import java.net.URL;
23 import java.util.concurrent.Future;
24 import java.util.concurrent.TimeUnit;
25
26 import javax.imageio.ImageIO;
27
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;
51
52 import com.google.gson.JsonSyntaxException;
53
54 /**
55  * The {@link WeatherCompanyForecastHandler} is responsible for pulling weather forecast
56  * information from the Weather Company API.
57  *
58  * API documentation is located here
59  * - https://docs.google.com/document/d/1eKCnKXI9xnoMGRRzOL1xPCBihNV2rOet08qpE_gArAY/edit
60  *
61  * @author Mark Hilbush - Initial contribution
62  */
63 @NonNullByDefault
64 public class WeatherCompanyForecastHandler extends WeatherCompanyAbstractHandler {
65     private static final String BASE_FORECAST_URL = "https://api.weather.com/v3/wx/forecast/daily/5day";
66
67     private final Logger logger = LoggerFactory.getLogger(WeatherCompanyForecastHandler.class);
68
69     private final LocaleProvider localeProvider;
70
71     private int refreshIntervalSeconds;
72     private String locationQueryString = "";
73     private String languageQueryString = "";
74
75     private @Nullable Future<?> refreshForecastJob;
76
77     private final Runnable refreshRunnable = new Runnable() {
78         @Override
79         public void run() {
80             refreshForecast();
81         }
82     };
83
84     public WeatherCompanyForecastHandler(Thing thing, TimeZoneProvider timeZoneProvider, HttpClient httpClient,
85             UnitProvider unitProvider, LocaleProvider localeProvider) {
86         super(thing, timeZoneProvider, httpClient, unitProvider);
87         this.localeProvider = localeProvider;
88     }
89
90     @Override
91     public void initialize() {
92         logger.debug("Forecast handler initializing with configuration: {}",
93                 getConfigAs(WeatherCompanyForecastConfig.class).toString());
94
95         refreshIntervalSeconds = getConfigAs(WeatherCompanyForecastConfig.class).refreshInterval * 60;
96         if (isValidLocation()) {
97             weatherDataCache.clear();
98             setLanguage();
99             scheduleRefreshJob();
100             updateStatus(isBridgeOnline() ? ThingStatus.ONLINE : ThingStatus.OFFLINE);
101         }
102     }
103
104     @Override
105     public void dispose() {
106         cancelRefreshJob();
107         updateStatus(ThingStatus.OFFLINE);
108     }
109
110     @Override
111     public void handleCommand(ChannelUID channelUID, Command command) {
112         if (command.equals(RefreshType.REFRESH)) {
113             State state = weatherDataCache.get(channelUID.getId());
114             if (state != null) {
115                 updateChannel(channelUID.getId(), state);
116             }
117         }
118     }
119
120     private boolean isValidLocation() {
121         boolean validLocation = false;
122         String locationType = getConfigAs(WeatherCompanyForecastConfig.class).locationType;
123         if (locationType == null) {
124             return validLocation;
125         }
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");
131                 } else {
132                     locationQueryString = "&postalKey=" + postalCode.replace(" ", "");
133                     validLocation = true;
134                 }
135                 break;
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");
140                 } else {
141                     locationQueryString = "&geocode=" + geocode.replace(" ", "");
142                     validLocation = true;
143                 }
144                 break;
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");
149                 } else {
150                     locationQueryString = "&iataCode=" + iataCode.replace(" ", "").toUpperCase();
151                     validLocation = true;
152                 }
153                 break;
154             default:
155                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Location Type is not set");
156                 break;
157         }
158         return validLocation;
159     }
160
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);
168         } else {
169             // Use what is set in the thing config
170             languageQueryString = "&language=" + language;
171         }
172     }
173
174     /*
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).
178      */
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();
195     }
196
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");
201             return;
202         }
203         logger.debug("Handler: Requesting forecast from The Weather Company API");
204         String response = executeApiRequest(buildForecastUrl());
205         if (response == null) {
206             return;
207         }
208         try {
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");
218             return;
219         }
220     }
221
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()));
233         }
234     }
235
236     private void updateDaypartForecast(Object daypartObject) {
237         DayPartDTO[] dayparts;
238         try {
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");
246             return;
247         }
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");
251             return;
252         }
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]));
288         }
289     }
290
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");
294         if (image != null) {
295             return new RawType(image, "image/png");
296         }
297         // Next try to get the N/A image
298         image = getImage("icons" + File.separator + "na.png");
299         if (image != null) {
300             return new RawType(image, "image/png");
301         }
302         // Couldn't get any icon image, so set to UNDEF
303         return UnDefType.UNDEF;
304     }
305
306     private byte @Nullable [] getImage(String iconPath) {
307         byte[] data = null;
308         URL url = FrameworkUtil.getBundle(getClass()).getResource(iconPath);
309         logger.trace("Path to icon image resource is: {}", url);
310         if (url != null) {
311             try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
312                 InputStream is = url.openStream();
313                 BufferedImage image = ImageIO.read(is);
314                 ImageIO.write(image, "png", out);
315                 out.flush();
316                 data = out.toByteArray();
317             } catch (IOException e) {
318                 logger.debug("I/O exception occurred getting image data: {}", e.getMessage(), e);
319             }
320         }
321         return data;
322     }
323
324     private void updateDaily(int day, String channelId, State state) {
325         updateChannel(CH_GROUP_FORECAST_DAY + String.valueOf(day) + "#" + channelId, state);
326     }
327
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);
332     }
333
334     /*
335      * The refresh job updates the daily forecast on the
336      * refresh interval set in the thing config
337      */
338     private void scheduleRefreshJob() {
339         logger.debug("Handler: Scheduling forecast refresh job in {} seconds", REFRESH_JOB_INITIAL_DELAY_SECONDS);
340         cancelRefreshJob();
341         refreshForecastJob = scheduler.scheduleWithFixedDelay(refreshRunnable, REFRESH_JOB_INITIAL_DELAY_SECONDS,
342                 refreshIntervalSeconds, TimeUnit.SECONDS);
343     }
344
345     private void cancelRefreshJob() {
346         if (refreshForecastJob != null) {
347             refreshForecastJob.cancel(true);
348             logger.debug("Handler: Canceling forecast refresh job");
349         }
350     }
351 }