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.darksky.internal.handler;
15 import static org.openhab.binding.darksky.internal.DarkSkyBindingConstants.*;
17 import java.util.Collections;
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.darksky.internal.config.DarkSkyAPIConfiguration;
26 import org.openhab.binding.darksky.internal.connection.DarkSkyConnection;
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.types.Command;
38 import org.openhab.core.types.RefreshType;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
43 * The {@link DarkSkyAPIHandler} is responsible for accessing the Dark Sky API.
45 * @author Christoph Weitkamp - Initial contribution
48 public class DarkSkyAPIHandler extends BaseBridgeHandler {
50 private final Logger logger = LoggerFactory.getLogger(DarkSkyAPIHandler.class);
52 public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Collections.singleton(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({}) DarkSkyConnection connection;
62 // keeps track of the parsed config
63 private @NonNullByDefault({}) DarkSkyAPIConfiguration config;
65 public DarkSkyAPIHandler(Bridge bridge, HttpClient httpClient, LocaleProvider localeProvider) {
67 this.httpClient = httpClient;
68 this.localeProvider = localeProvider;
72 public void initialize() {
73 logger.debug("Initialize Dark Sky API handler '{}'.", getThing().getUID());
74 config = getConfigAs(DarkSkyAPIConfiguration.class);
76 boolean configValid = true;
77 if (config.apikey == null || config.apikey.trim().isEmpty()) {
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 (!DarkSkyAPIConfiguration.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 (DarkSkyAPIConfiguration.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 DarkSkyConnection(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 Dark Sky 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 Dark Sky binding is a read-only binding and cannot handle command '{}'.", command);
141 public void childHandlerInitialized(ThingHandler childHandler, Thing childThing) {
142 scheduler.schedule(() -> {
143 updateThing((DarkSkyWeatherAndForecastHandler) 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((DarkSkyWeatherAndForecastHandler) thing.getHandler(), thing))) {
168 status = ThingStatus.ONLINE;
171 updateStatus(status);
174 private ThingStatus updateThing(@Nullable DarkSkyWeatherAndForecastHandler handler, Thing thing) {
175 if (handler != null && 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 DarkSkyAPIConfiguration getDarkSkyAPIConfig() {