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;
49 import com.google.gson.JsonSyntaxException;
52 * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
55 * @author Gaƫl L'hopital - Initial contribution
59 public class OpenUVBridgeHandler extends BaseBridgeHandler {
60 private static final String QUERY_URL = "https://api.openuv.io/api/v1/uv?lat=%s&lng=%s&alt=%s";
61 private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
63 private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
64 private final Properties header = new Properties();
65 private final Gson gson;
66 private final LocationProvider locationProvider;
67 private final TranslationProvider i18nProvider;
68 private final LocaleProvider localeProvider;
70 private @Nullable ScheduledFuture<?> reconnectJob;
72 public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
73 LocaleProvider localeProvider, Gson gson) {
76 this.locationProvider = locationProvider;
77 this.i18nProvider = i18nProvider;
78 this.localeProvider = localeProvider;
82 public void initialize() {
83 logger.debug("Initializing OpenUV API bridge handler.");
84 BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
85 if (config.apikey.isEmpty()) {
86 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
87 "@text/offline.config-error-unknown-apikey");
90 header.put("x-access-token", config.apikey);
95 public void dispose() {
96 ScheduledFuture<?> job = this.reconnectJob;
97 if (job != null && !job.isCancelled()) {
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 url = String.format(QUERY_URL, latitude, longitude, altitude);
119 String jsonData = "";
121 jsonData = HttpUtil.executeUrl("GET", url, header, null, null, REQUEST_TIMEOUT_MS);
122 OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
123 if (uvResponse != null) {
124 String error = uvResponse.getError();
126 updateStatus(ThingStatus.ONLINE);
127 return uvResponse.getResult();
129 throw new OpenUVException(error);
131 } catch (JsonSyntaxException e) {
132 logger.debug("No valid json received when calling `{}` : {}", url, jsonData);
133 } catch (IOException e) {
134 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
135 } catch (OpenUVException e) {
136 if (e.isQuotaError()) {
137 LocalDateTime tomorrowMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
140 .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
142 reconnectJob = scheduler.schedule(this::initiateConnexion,
143 Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);
145 updateStatus(ThingStatus.OFFLINE,
146 e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
154 public Collection<Class<? extends ThingHandlerService>> getServices() {
155 return Collections.singleton(OpenUVDiscoveryService.class);
158 public @Nullable PointType getLocation() {
159 return locationProvider.getLocation();
162 public TranslationProvider getI18nProvider() {
166 public LocaleProvider getLocaleProvider() {
167 return localeProvider;