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