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.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 REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
64 private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
65 private final Properties header = new Properties();
66 private final Gson gson;
67 private final LocationProvider locationProvider;
68 private final TranslationProvider i18nProvider;
69 private final LocaleProvider localeProvider;
71 private Optional<ScheduledFuture<?>> reconnectJob = Optional.empty();
73 public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
74 LocaleProvider localeProvider, Gson gson) {
77 this.locationProvider = locationProvider;
78 this.i18nProvider = i18nProvider;
79 this.localeProvider = localeProvider;
83 public void initialize() {
84 logger.debug("Initializing OpenUV API bridge handler.");
85 BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
86 if (config.apikey.isEmpty()) {
87 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
88 "@text/offline.config-error-unknown-apikey");
91 header.put("x-access-token", config.apikey);
96 public void dispose() {
97 reconnectJob.ifPresent(job -> job.cancel(true));
98 reconnectJob = Optional.empty();
102 public void handleCommand(ChannelUID channelUID, Command command) {
103 if (command instanceof RefreshType) {
107 logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
110 private void initiateConnexion() {
111 // Just checking if the provided api key is a valid one by making a fake call
112 getUVData("0", "0", "0");
115 public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
116 String url = String.format(QUERY_URL, latitude, longitude, altitude);
117 String jsonData = "";
119 jsonData = HttpUtil.executeUrl("GET", url, 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 (JsonSyntaxException e) {
130 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
131 String.format("Invalid json received when calling `%s` : %s", url, jsonData));
132 } catch (IOException e) {
133 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
134 } catch (OpenUVException e) {
135 if (e.isQuotaError()) {
136 LocalDateTime tomorrowMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
138 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
139 .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
141 reconnectJob = Optional.of(scheduler.schedule(this::initiateConnexion,
142 Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES));
144 updateStatus(ThingStatus.OFFLINE,
145 e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
153 public Collection<Class<? extends ThingHandlerService>> getServices() {
154 return Set.of(OpenUVDiscoveryService.class);
157 public @Nullable PointType getLocation() {
158 return locationProvider.getLocation();
161 public TranslationProvider getI18nProvider() {
165 public LocaleProvider getLocaleProvider() {
166 return localeProvider;