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.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.Collections;
21 import java.util.Properties;
22 import java.util.concurrent.ScheduledFuture;
23 import java.util.concurrent.TimeUnit;
25 import org.eclipse.jdt.annotation.NonNullByDefault;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.openhab.binding.openuv.internal.OpenUVException;
28 import org.openhab.binding.openuv.internal.config.BridgeConfiguration;
29 import org.openhab.binding.openuv.internal.discovery.OpenUVDiscoveryService;
30 import org.openhab.binding.openuv.internal.json.OpenUVResponse;
31 import org.openhab.binding.openuv.internal.json.OpenUVResult;
32 import org.openhab.core.i18n.LocaleProvider;
33 import org.openhab.core.i18n.LocationProvider;
34 import org.openhab.core.i18n.TranslationProvider;
35 import org.openhab.core.io.net.http.HttpUtil;
36 import org.openhab.core.library.types.PointType;
37 import org.openhab.core.thing.Bridge;
38 import org.openhab.core.thing.ChannelUID;
39 import org.openhab.core.thing.ThingStatus;
40 import org.openhab.core.thing.ThingStatusDetail;
41 import org.openhab.core.thing.binding.BaseBridgeHandler;
42 import org.openhab.core.thing.binding.ThingHandlerService;
43 import org.openhab.core.types.Command;
44 import org.openhab.core.types.RefreshType;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
48 import com.google.gson.Gson;
51 * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
54 * @author Gaƫl L'hopital - Initial contribution
58 public class OpenUVBridgeHandler extends BaseBridgeHandler {
59 private static final String QUERY_URL = "https://api.openuv.io/api/v1/uv?lat=%s&lng=%s&alt=%s";
60 private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
62 private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
63 private final Properties header = new Properties();
64 private final Gson gson;
65 private final LocationProvider locationProvider;
66 private final TranslationProvider i18nProvider;
67 private final LocaleProvider localeProvider;
69 private @Nullable ScheduledFuture<?> reconnectJob;
71 public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
72 LocaleProvider localeProvider, Gson gson) {
75 this.locationProvider = locationProvider;
76 this.i18nProvider = i18nProvider;
77 this.localeProvider = localeProvider;
81 public void initialize() {
82 logger.debug("Initializing OpenUV API bridge handler.");
83 BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
84 if (config.apikey.isEmpty()) {
85 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
86 "@text/offline.config-error-unknown-apikey");
89 header.put("x-access-token", config.apikey);
94 public void dispose() {
95 ScheduledFuture<?> job = this.reconnectJob;
96 if (job != null && !job.isCancelled()) {
103 public void handleCommand(ChannelUID channelUID, Command command) {
104 if (command instanceof RefreshType) {
108 logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
111 private void initiateConnexion() {
112 // Just checking if the provided api key is a valid one by making a fake call
113 getUVData("0", "0", "0");
116 public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
118 String jsonData = HttpUtil.executeUrl("GET", String.format(QUERY_URL, latitude, longitude, altitude),
119 header, null, null, REQUEST_TIMEOUT_MS);
120 OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
121 if (uvResponse != null) {
122 String error = uvResponse.getError();
124 updateStatus(ThingStatus.ONLINE);
125 return uvResponse.getResult();
127 throw new OpenUVException(error);
129 } catch (IOException e) {
130 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
131 } catch (OpenUVException e) {
132 if (e.isQuotaError()) {
133 LocalDate today = LocalDate.now();
134 LocalDate tomorrow = today.plusDays(1);
135 LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);
137 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
138 .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
140 reconnectJob = scheduler.schedule(this::initiateConnexion,
141 Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);
143 updateStatus(ThingStatus.OFFLINE,
144 e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
152 public Collection<Class<? extends ThingHandlerService>> getServices() {
153 return Collections.singleton(OpenUVDiscoveryService.class);
156 public @Nullable PointType getLocation() {
157 return locationProvider.getLocation();
160 public TranslationProvider getI18nProvider() {
164 public LocaleProvider getLocaleProvider() {
165 return localeProvider;