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.handler;
15 import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*;
17 import java.util.List;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.eclipse.jetty.client.HttpClient;
25 import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapAPIConfiguration;
26 import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConnection;
27 import org.openhab.core.config.core.Configuration;
28 import org.openhab.core.i18n.LocaleProvider;
29 import org.openhab.core.thing.Bridge;
30 import org.openhab.core.thing.ChannelUID;
31 import org.openhab.core.thing.Thing;
32 import org.openhab.core.thing.ThingStatus;
33 import org.openhab.core.thing.ThingStatusDetail;
34 import org.openhab.core.thing.ThingTypeUID;
35 import org.openhab.core.thing.binding.BaseBridgeHandler;
36 import org.openhab.core.thing.binding.ThingHandler;
37 import org.openhab.core.thing.util.ThingHandlerHelper;
38 import org.openhab.core.types.Command;
39 import org.openhab.core.types.RefreshType;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
44 * The {@link OpenWeatherMapAPIHandler} is responsible for accessing the OpenWeatherMap API.
46 * @author Christoph Weitkamp - Initial contribution
49 public class OpenWeatherMapAPIHandler extends BaseBridgeHandler {
51 private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapAPIHandler.class);
53 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_API);
55 private static final long INITIAL_DELAY_IN_SECONDS = 15;
57 private @Nullable ScheduledFuture<?> refreshJob;
59 private final HttpClient httpClient;
60 private final LocaleProvider localeProvider;
61 private @NonNullByDefault({}) OpenWeatherMapConnection connection;
63 // keeps track of the parsed config
64 private @NonNullByDefault({}) OpenWeatherMapAPIConfiguration config;
66 public OpenWeatherMapAPIHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
68 this.httpClient = httpClient;
69 this.localeProvider = localeProvider;
73 public void initialize() {
74 logger.debug("Initialize OpenWeatherMap API handler '{}'.", getThing().getUID());
75 config = getConfigAs(OpenWeatherMapAPIConfiguration.class);
77 boolean configValid = true;
78 if (config.apikey.isBlank()) {
79 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
80 "@text/offline.conf-error-missing-apikey");
83 int refreshInterval = config.refreshInterval;
84 if (refreshInterval < 1) {
85 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
86 "@text/offline.conf-error-not-supported-refreshInterval");
89 String language = config.language;
90 if (language != null && !(language = language.trim()).isEmpty()) {
91 if (!OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language.toLowerCase())) {
92 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
93 "@text/offline.conf-error-not-supported-language");
97 language = localeProvider.getLocale().getLanguage();
98 if (OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language)) {
99 logger.debug("Language set to '{}'.", language);
100 Configuration editConfig = editConfiguration();
101 editConfig.put(CONFIG_LANGUAGE, language);
102 updateConfiguration(editConfig);
107 connection = new OpenWeatherMapConnection(this, httpClient);
109 updateStatus(ThingStatus.UNKNOWN);
111 ScheduledFuture<?> localRefreshJob = refreshJob;
112 if (localRefreshJob == null || localRefreshJob.isCancelled()) {
113 logger.debug("Start refresh job at interval {} min.", refreshInterval);
114 refreshJob = scheduler.scheduleWithFixedDelay(this::updateThings, INITIAL_DELAY_IN_SECONDS,
115 TimeUnit.MINUTES.toSeconds(refreshInterval), TimeUnit.SECONDS);
121 public void dispose() {
122 logger.debug("Dispose OpenWeatherMap API handler '{}'.", getThing().getUID());
123 ScheduledFuture<?> localRefreshJob = refreshJob;
124 if (localRefreshJob != null && !localRefreshJob.isCancelled()) {
125 logger.debug("Stop refresh job.");
126 if (localRefreshJob.cancel(true)) {
133 public void handleCommand(ChannelUID channelUID, Command command) {
134 if (command instanceof RefreshType) {
135 scheduler.schedule(this::updateThings, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
137 logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
142 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
143 scheduler.schedule(() -> {
144 updateThing((AbstractOpenWeatherMapHandler) childHandler, childThing);
145 determineBridgeStatus();
146 }, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
150 public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
151 determineBridgeStatus();
154 private void determineBridgeStatus() {
155 ThingStatus status = ThingStatus.ONLINE;
156 List<Thing> childs = getThing().getThings();
157 if (!childs.isEmpty()) {
158 status = ThingStatus.OFFLINE;
159 for (Thing thing : childs) {
160 if (ThingStatus.ONLINE.equals(thing.getStatus())) {
161 status = ThingStatus.ONLINE;
166 updateStatus(status);
169 private void updateThings() {
170 ThingStatus status = ThingStatus.ONLINE;
171 List<Thing> childs = getThing().getThings();
172 if (!childs.isEmpty()) {
173 status = ThingStatus.OFFLINE;
174 for (Thing thing : childs) {
175 if (ThingStatus.ONLINE.equals(updateThing((AbstractOpenWeatherMapHandler) thing.getHandler(), thing))) {
176 status = ThingStatus.ONLINE;
180 updateStatus(status);
183 private ThingStatus updateThing(@Nullable AbstractOpenWeatherMapHandler handler, Thing thing) {
184 if (handler != null && ThingHandlerHelper.isHandlerInitialized(handler) && connection != null) {
185 handler.updateData(connection);
186 return thing.getStatus();
188 logger.debug("Cannot update weather data of thing '{}' as location handler is null.", thing.getUID());
189 return ThingStatus.OFFLINE;
193 public OpenWeatherMapAPIConfiguration getOpenWeatherMapAPIConfig() {