]> git.basschouten.com Git - openhab-addons.git/blob
600c3bc2e9bc3df6ac9751e6b7cd565d38ee98a3
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.openweathermap.internal.handler;
14
15 import static org.openhab.binding.openweathermap.internal.OpenWeatherMapBindingConstants.*;
16
17 import java.util.List;
18 import java.util.Set;
19 import java.util.concurrent.ScheduledFuture;
20 import java.util.concurrent.TimeUnit;
21
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;
42
43 /**
44  * The {@link OpenWeatherMapAPIHandler} is responsible for accessing the OpenWeatherMap API.
45  *
46  * @author Christoph Weitkamp - Initial contribution
47  */
48 @NonNullByDefault
49 public class OpenWeatherMapAPIHandler extends BaseBridgeHandler {
50
51     private final Logger logger = LoggerFactory.getLogger(OpenWeatherMapAPIHandler.class);
52
53     public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_WEATHER_API);
54
55     private static final long INITIAL_DELAY_IN_SECONDS = 15;
56
57     private @Nullable ScheduledFuture<?> refreshJob;
58
59     private final HttpClient httpClient;
60     private final LocaleProvider localeProvider;
61     private @NonNullByDefault({}) OpenWeatherMapConnection connection;
62
63     // keeps track of the parsed config
64     private @NonNullByDefault({}) OpenWeatherMapAPIConfiguration config;
65
66     public OpenWeatherMapAPIHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
67         super(bridge);
68         this.httpClient = httpClient;
69         this.localeProvider = localeProvider;
70     }
71
72     @Override
73     public void initialize() {
74         logger.debug("Initialize OpenWeatherMap API handler '{}'.", getThing().getUID());
75         config = getConfigAs(OpenWeatherMapAPIConfiguration.class);
76
77         boolean configValid = true;
78         if (config.apikey.isBlank()) {
79             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
80                     "@text/offline.conf-error-missing-apikey");
81             configValid = false;
82         }
83         int refreshInterval = config.refreshInterval;
84         if (refreshInterval < 1) {
85             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
86                     "@text/offline.conf-error-not-supported-refreshInterval");
87             configValid = false;
88         }
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");
94                 configValid = false;
95             }
96         } else {
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);
103             }
104         }
105
106         if (configValid) {
107             connection = new OpenWeatherMapConnection(this, httpClient);
108
109             updateStatus(ThingStatus.UNKNOWN);
110
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);
116             }
117         }
118     }
119
120     @Override
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)) {
127                 refreshJob = null;
128             }
129         }
130     }
131
132     @Override
133     public void handleCommand(ChannelUID channelUID, Command command) {
134         if (command instanceof RefreshType) {
135             scheduler.schedule(this::updateThings, INITIAL_DELAY_IN_SECONDS, TimeUnit.SECONDS);
136         } else {
137             logger.debug("The OpenWeatherMap binding is a read-only binding and cannot handle command '{}'.", command);
138         }
139     }
140
141     @Override
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);
147     }
148
149     @Override
150     public void childHandlerDisposed(ThingHandler childHandler, Thing childThing) {
151         determineBridgeStatus();
152     }
153
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;
162                     break;
163                 }
164             }
165         }
166         updateStatus(status);
167     }
168
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;
177                 }
178             }
179         }
180         updateStatus(status);
181     }
182
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();
187         } else {
188             logger.debug("Cannot update weather data of thing '{}' as location handler is null.", thing.getUID());
189             return ThingStatus.OFFLINE;
190         }
191     }
192
193     public OpenWeatherMapAPIConfiguration getOpenWeatherMapAPIConfig() {
194         return config;
195     }
196 }