2 * Copyright (c) 2010-2023 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;
21 import java.util.stream.Collectors;
23 import org.eclipse.jdt.annotation.NonNullByDefault;
24 import org.eclipse.jdt.annotation.Nullable;
25 import org.eclipse.jetty.client.HttpClient;
26 import org.openhab.binding.openweathermap.internal.config.OpenWeatherMapAPIConfiguration;
27 import org.openhab.binding.openweathermap.internal.connection.OpenWeatherMapConnection;
28 import org.openhab.core.config.core.Configuration;
29 import org.openhab.core.i18n.LocaleProvider;
30 import org.openhab.core.thing.Bridge;
31 import org.openhab.core.thing.ChannelUID;
32 import org.openhab.core.thing.Thing;
33 import org.openhab.core.thing.ThingStatus;
34 import org.openhab.core.thing.ThingStatusDetail;
35 import org.openhab.core.thing.ThingTypeUID;
36 import org.openhab.core.thing.binding.BaseBridgeHandler;
37 import org.openhab.core.thing.binding.ThingHandler;
38 import org.openhab.core.thing.util.ThingHandlerHelper;
39 import org.openhab.core.types.Command;
40 import org.openhab.core.types.RefreshType;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
45 * The {@link OpenWeatherMapAPIHandler} is responsible for accessing the OpenWeatherMap API.
47 * @author Christoph Weitkamp - Initial contribution
50 public class OpenWeatherMapAPIHandler extends BaseBridgeHandler {
52 private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapAPIHandler.class);
54 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_API);
56 private static final long INITIAL_DELAY_IN_SECONDS = 15;
58 private @Nullable ScheduledFuture<?> refreshJob;
60 private final HttpClient httpClient;
61 private final LocaleProvider localeProvider;
62 private @NonNullByDefault({}) OpenWeatherMapConnection connection;
64 // keeps track of the parsed config
65 private @NonNullByDefault({}) OpenWeatherMapAPIConfiguration config;
67 public OpenWeatherMapAPIHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
69 this.httpClient = httpClient;
70 this.localeProvider = localeProvider;
74 public void initialize() {
75 logger.debug("Initialize OpenWeatherMap API handler '{}'.", getThing().getUID());
76 config = getConfigAs(OpenWeatherMapAPIConfiguration.class);
78 boolean configValid = true;
79 if (config.apikey.isBlank()) {
80 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
81 "@text/offline.conf-error-missing-apikey");
84 int refreshInterval = config.refreshInterval;
85 if (refreshInterval < 1) {
86 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
87 "@text/offline.conf-error-not-supported-refreshInterval");
90 String language = config.language;
91 if (language != null && !(language = language.trim()).isEmpty()) {
92 if (!OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language.toLowerCase())) {
93 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
94 "@text/offline.conf-error-not-supported-language");
98 language = localeProvider.getLocale().getLanguage();
99 if (OpenWeatherMapAPIConfiguration.SUPPORTED_LANGUAGES.contains(language)) {
100 logger.debug("Language set to '{}'.", language);
101 Configuration editConfig = editConfiguration();
102 editConfig.put(CONFIG_LANGUAGE, language);
103 updateConfiguration(editConfig);
108 connection = new OpenWeatherMapConnection(this, httpClient);
110 updateStatus(ThingStatus.UNKNOWN);
112 ScheduledFuture<?> localRefreshJob = refreshJob;
113 if (localRefreshJob == null || localRefreshJob.isCancelled()) {
114 logger.debug("Start refresh job at interval {} min.", refreshInterval);
115 refreshJob = scheduler.scheduleWithFixedDelay(this::updateThings, INITIAL_DELAY_IN_SECONDS,
116 TimeUnit.MINUTES.toSeconds(refreshInterval), TimeUnit.SECONDS);
122 public void dispose() {
123 logger.debug("Dispose OpenWeatherMap API handler '{}'.", getThing().getUID());
124 ScheduledFuture<?> localRefreshJob = refreshJob;
125 if (localRefreshJob != null && !localRefreshJob.isCancelled()) {
126 logger.debug("Stop refresh job.");
127 if (localRefreshJob.cancel(true)) {
134 public void handleCommand(ChannelUID channelUID, Command command) {
135 if (command instanceof RefreshType) {
136 scheduler.schedule(this::updateThings, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
138 logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
143 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
144 scheduler.schedule(() -> {
145 updateThing((AbstractOpenWeatherMapHandler) childHandler, childThing);
146 determineBridgeStatus();
147 }, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
151 public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
152 determineBridgeStatus();
155 private void determineBridgeStatus() {
156 ThingStatus status = ThingStatus.ONLINE;
157 List<Thing> childs = getThing().getThings().stream().filter(Thing::isEnabled).collect(Collectors.toList());
158 if (!childs.isEmpty()) {
159 status = ThingStatus.OFFLINE;
160 for (Thing thing : childs) {
161 if (ThingStatus.ONLINE.equals(thing.getStatus())) {
162 status = ThingStatus.ONLINE;
167 updateStatus(status);
170 private void updateThings() {
171 ThingStatus status = ThingStatus.ONLINE;
172 List<Thing> childs = getThing().getThings().stream().filter(Thing::isEnabled).collect(Collectors.toList());
173 if (!childs.isEmpty()) {
174 status = ThingStatus.OFFLINE;
175 for (Thing thing : childs) {
176 if (ThingStatus.ONLINE.equals(updateThing((AbstractOpenWeatherMapHandler) thing.getHandler(), thing))) {
177 status = ThingStatus.ONLINE;
181 updateStatus(status);
184 private ThingStatus updateThing(@Nullable AbstractOpenWeatherMapHandler handler, Thing thing) {
185 if (handler != null && ThingHandlerHelper.isHandlerInitialized(handler) && connection != null) {
186 handler.updateData(connection);
187 return thing.getStatus();
189 logger.debug("Cannot update weather data of thing '{}' as location handler is null.", thing.getUID());
190 return ThingStatus.OFFLINE;
194 public OpenWeatherMapAPIConfiguration getOpenWeatherMapAPIConfig() {