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.openuv.internal.handler;
15 import java.io.IOException;
16 import java.time.Duration;
17 import java.time.LocalDate;
18 import java.time.LocalDateTime;
19 import java.util.Collection;
20 import java.util.Optional;
21 import java.util.Properties;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.openhab.binding.openuv.internal.OpenUVException;
29 import org.openhab.binding.openuv.internal.config.BridgeConfiguration;
30 import org.openhab.binding.openuv.internal.discovery.OpenUVDiscoveryService;
31 import org.openhab.binding.openuv.internal.json.OpenUVResponse;
32 import org.openhab.binding.openuv.internal.json.OpenUVResult;
33 import org.openhab.core.i18n.LocaleProvider;
34 import org.openhab.core.i18n.LocationProvider;
35 import org.openhab.core.i18n.TranslationProvider;
36 import org.openhab.core.io.net.http.HttpUtil;
37 import org.openhab.core.library.types.PointType;
38 import org.openhab.core.thing.Bridge;
39 import org.openhab.core.thing.ChannelUID;
40 import org.openhab.core.thing.ThingStatus;
41 import org.openhab.core.thing.ThingStatusDetail;
42 import org.openhab.core.thing.binding.BaseBridgeHandler;
43 import org.openhab.core.thing.binding.ThingHandlerService;
44 import org.openhab.core.types.Command;
45 import org.openhab.core.types.RefreshType;
46 import org.slf4j.Logger;
47 import org.slf4j.LoggerFactory;
49 import com.google.gson.Gson;
50 import com.google.gson.JsonSyntaxException;
53 * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
56 * @author Gaƫl L'hopital - Initial contribution
60 public class OpenUVBridgeHandler extends BaseBridgeHandler {
61 private static final String QUERY_URL = "https://api.openuv.io/api/v1/uv?lat=%s&lng=%s&alt=%s";
62 private static final int RECONNECT_DELAY_MIN = 5;
63 private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
65 private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
66 private final Properties header = new Properties();
67 private final Gson gson;
68 private final LocationProvider locationProvider;
69 private final TranslationProvider i18nProvider;
70 private final LocaleProvider localeProvider;
72 private Optional<ScheduledFuture<?>> reconnectJob = Optional.empty();
73 private boolean keyVerified;
75 public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
76 LocaleProvider localeProvider, Gson gson) {
79 this.locationProvider = locationProvider;
80 this.i18nProvider = i18nProvider;
81 this.localeProvider = localeProvider;
85 public void initialize() {
86 logger.debug("Initializing OpenUV API bridge handler.");
88 BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
89 if (config.apikey.isEmpty()) {
90 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
91 "@text/offline.config-error-unknown-apikey");
94 header.put("x-access-token", config.apikey);
99 public void dispose() {
104 public void handleCommand(ChannelUID channelUID, Command command) {
105 if (command instanceof RefreshType) {
109 logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
112 private void initiateConnexion() {
113 // Just checking if the provided api key is a valid one by making a fake call
114 getUVData("0", "0", "0");
117 public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
118 String statusMessage = "";
119 ThingStatusDetail statusDetail = ThingStatusDetail.COMMUNICATION_ERROR;
120 String url = String.format(QUERY_URL, latitude, longitude, altitude);
121 String jsonData = "";
123 jsonData = HttpUtil.executeUrl("GET", url, header, null, null, REQUEST_TIMEOUT_MS);
124 OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
125 if (uvResponse != null) {
126 String error = uvResponse.getError();
128 updateStatus(ThingStatus.ONLINE);
130 return uvResponse.getResult();
132 throw new OpenUVException(error);
134 } catch (JsonSyntaxException e) {
135 if (jsonData.contains("MongoError")) {
136 statusMessage = String.format("@text/offline.comm-error-faultly-service [ \"%d\" ]",
137 RECONNECT_DELAY_MIN);
138 scheduleReconnectJob(RECONNECT_DELAY_MIN);
140 statusDetail = ThingStatusDetail.NONE;
141 statusMessage = String.format("@text/offline.invalid-json [ \"%s\" ]", url);
142 logger.debug("{} : {}", statusMessage, jsonData);
144 } catch (IOException e) {
145 statusMessage = String.format("@text/offline.comm-error-ioexception [ \"%s\",\"%d\" ]", e.getMessage(),
146 RECONNECT_DELAY_MIN);
147 scheduleReconnectJob(RECONNECT_DELAY_MIN);
148 } catch (OpenUVException e) {
149 if (e.isQuotaError()) {
150 LocalDateTime nextMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
151 statusMessage = String.format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]",
152 nextMidnight.toString());
153 scheduleReconnectJob(Duration.between(LocalDateTime.now(), nextMidnight).toMinutes());
154 } else if (e.isApiKeyError()) {
156 statusMessage = String.format("@text/offline.api-key-not-recognized [ \"%d\" ]",
157 RECONNECT_DELAY_MIN);
158 scheduleReconnectJob(RECONNECT_DELAY_MIN);
160 statusDetail = ThingStatusDetail.CONFIGURATION_ERROR;
164 updateStatus(ThingStatus.OFFLINE, statusDetail, statusMessage);
168 private void scheduleReconnectJob(long delay) {
170 reconnectJob = Optional.of(scheduler.schedule(this::initiateConnexion, delay, TimeUnit.MINUTES));
173 private void freeReconnectJob() {
174 reconnectJob.ifPresent(job -> job.cancel(true));
175 reconnectJob = Optional.empty();
179 public Collection<Class<? extends ThingHandlerService>> getServices() {
180 return Set.of(OpenUVDiscoveryService.class);
183 public @Nullable PointType getLocation() {
184 return locationProvider.getLocation();
187 public TranslationProvider getI18nProvider() {
191 public LocaleProvider getLocaleProvider() {
192 return localeProvider;