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.handler;
15 import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*;
18 import java.util.concurrent.ScheduledFuture;
19 import java.util.concurrent.TimeUnit;
21 import org.eclipse.jdt.annotation.NonNullByDefault;
22 import org.eclipse.jdt.annotation.Nullable;
23 import org.eclipse.jetty.client.HttpClient;
24 import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapAPIConfiguration;
25 import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConnection;
26 import org.openhab.core.config.core.Configuration;
27 import org.openhab.core.i18n.LocaleProvider;
28 import org.openhab.core.thing.Bridge;
29 import org.openhab.core.thing.ChannelUID;
30 import org.openhab.core.thing.Thing;
31 import org.openhab.core.thing.ThingStatus;
32 import org.openhab.core.thing.ThingStatusDetail;
33 import org.openhab.core.thing.ThingTypeUID;
34 import org.openhab.core.thing.binding.BaseBridgeHandler;
35 import org.openhab.core.thing.binding.ThingHandler;
36 import org.openhab.core.thing.util.ThingHandlerHelper;
37 import org.openhab.core.types.Command;
38 import org.openhab.core.types.RefreshType;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * The {@link OpenWeatherMapAPIHandler} is responsible for accessing the OpenWeatherMap API.
45 * @author Christoph Weitkamp - Initial contribution
48 public class OpenWeatherMapAPIHandler extends BaseBridgeHandler {
50 private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapAPIHandler.class);
52 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_API);
54 private static final long INITIAL_DELAY_IN_SECONDS = 15;
56 private @Nullable ScheduledFuture<?> refreshJob;
58 private final HttpClient httpClient;
59 private final LocaleProvider localeProvider;
60 private @NonNullByDefault({}) OpenWeatherMapConnection connection;
62 // keeps track of the parsed config
63 private @NonNullByDefault({}) OpenWeatherMapAPIConfiguration config;
65 public OpenWeatherMapAPIHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
67 this.httpClient = httpClient;
68 this.localeProvider = localeProvider;
72 public void initialize() {
73 logger.debug("Initialize OpenWeatherMap API handler '{}'.", getThing().getUID());
74 config = getConfigAs(OpenWeatherMapAPIConfiguration.class);
76 boolean configValid = true;
77 if (config.apikey.isBlank()) {
78 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
79 "@text/offline.conf-error-missing-apikey");
82 int refreshInterval = config.refreshInterval;
83 if (refreshInterval < 1) {
84 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
85 "@text/offline.conf-error-not-supported-refreshInterval");
88 String language = config.language;
89 if (language != null && !(language = language.trim()).isEmpty()) {
90 if (!OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language.toLowerCase())) {
91 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
92 "@text/offline.conf-error-not-supported-language");
96 language = localeProvider.getLocale().getLanguage();
97 if (OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language)) {
98 logger.debug("Language set to '{}'.", language);
99 Configuration editConfig = editConfiguration();
100 editConfig.put(CONFIG_LANGUAGE, language);
101 updateConfiguration(editConfig);
106 connection = new OpenWeatherMapConnection(this, httpClient);
108 updateStatus(ThingStatus.UNKNOWN);
110 ScheduledFuture<?> localRefreshJob = refreshJob;
111 if (localRefreshJob == null || localRefreshJob.isCancelled()) {
112 logger.debug("Start refresh job at interval {} min.", refreshInterval);
113 refreshJob = scheduler.scheduleWithFixedDelay(this::updateThings, INITIAL_DELAY_IN_SECONDS,
114 TimeUnit.MINUTES.toSeconds(refreshInterval), TimeUnit.SECONDS);
120 public void dispose() {
121 logger.debug("Dispose OpenWeatherMap API handler '{}'.", getThing().getUID());
122 ScheduledFuture<?> localRefreshJob = refreshJob;
123 if (localRefreshJob != null && !localRefreshJob.isCancelled()) {
124 logger.debug("Stop refresh job.");
125 if (localRefreshJob.cancel(true)) {
132 public void handleCommand(ChannelUID channelUID, Command command) {
133 if (command instanceof RefreshType) {
134 scheduler.schedule(this::updateThings, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
136 logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
141 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
142 scheduler.schedule(() -> {
143 updateThing((AbstractOpenWeatherMapHandler) childHandler, childThing);
144 determineBridgeStatus();
145 }, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
149 public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
150 determineBridgeStatus();
153 private void determineBridgeStatus() {
154 ThingStatus status = ThingStatus.OFFLINE;
155 for (Thing thing : getThing().getThings()) {
156 if (ThingStatus.ONLINE.equals(thing.getStatus())) {
157 status = ThingStatus.ONLINE;
161 updateStatus(status);
164 private void updateThings() {
165 ThingStatus status = ThingStatus.OFFLINE;
166 for (Thing thing : getThing().getThings()) {
167 if (ThingStatus.ONLINE.equals(updateThing((AbstractOpenWeatherMapHandler) thing.getHandler(), thing))) {
168 status = ThingStatus.ONLINE;
171 updateStatus(status);
174 private ThingStatus updateThing(@Nullable AbstractOpenWeatherMapHandler handler, Thing thing) {
175 if (handler != null && ThingHandlerHelper.isHandlerInitialized(handler) && connection != null) {
176 handler.updateData(connection);
177 return thing.getStatus();
179 logger.debug("Cannot update weather data of thing '{}' as location handler is null.", thing.getUID());
180 return ThingStatus.OFFLINE;
184 public OpenWeatherMapAPIConfiguration getOpenWeatherMapAPIConfig() {