2 * Copyright (c) 2010-2020 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.LocationProvider;
33 import org.openhab.core.io.net.http.HttpUtil;
34 import org.openhab.core.library.types.PointType;
35 import org.openhab.core.thing.Bridge;
36 import org.openhab.core.thing.ChannelUID;
37 import org.openhab.core.thing.ThingStatus;
38 import org.openhab.core.thing.ThingStatusDetail;
39 import org.openhab.core.thing.binding.BaseBridgeHandler;
40 import org.openhab.core.thing.binding.ThingHandlerService;
41 import org.openhab.core.types.Command;
42 import org.openhab.core.types.RefreshType;
43 import org.slf4j.Logger;
44 import org.slf4j.LoggerFactory;
46 import com.google.gson.Gson;
49 * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
52 * @author Gaƫl L'hopital - Initial contribution
56 public class OpenUVBridgeHandler extends BaseBridgeHandler {
57 private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
59 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 Properties header = new Properties();
64 private final Gson gson;
66 private final LocationProvider locationProvider;
67 private @Nullable ScheduledFuture<?> reconnectJob;
69 public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, Gson gson) {
72 this.locationProvider = locationProvider;
76 public void initialize() {
77 logger.debug("Initializing OpenUV API bridge handler.");
78 BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
79 if (config.apikey.isEmpty()) {
80 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
81 "Parameter 'apikey' must be configured.");
83 header.put("x-access-token", config.apikey);
89 public void dispose() {
90 ScheduledFuture<?> job = this.reconnectJob;
91 if (job != null && !job.isCancelled()) {
98 public void handleCommand(ChannelUID channelUID, Command command) {
99 if (command instanceof RefreshType) {
102 logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
106 private void initiateConnexion() {
107 // Check if the provided api key is valid for use with the OpenUV service
108 getUVData("0", "0", "0");
111 public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
113 String jsonData = HttpUtil.executeUrl("GET", String.format(QUERY_URL, latitude, longitude, altitude),
114 header, null, null, REQUEST_TIMEOUT_MS);
115 OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
116 if (uvResponse.getError() == null) {
117 updateStatus(ThingStatus.ONLINE);
118 return uvResponse.getResult();
120 throw new OpenUVException(uvResponse.getError());
122 } catch (IOException e) {
123 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
124 } catch (OpenUVException e) {
125 if (e.isQuotaError()) {
126 LocalDate today = LocalDate.now();
127 LocalDate tomorrow = today.plusDays(1);
128 LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);
130 String message = "Quota Exceeded, going OFFLINE for today, will retry at : "
131 + tomorrowMidnight.toString();
132 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
134 reconnectJob = scheduler.schedule(this::initiateConnexion,
135 Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);
136 } else if (e.isApiKeyError()) {
137 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
139 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, e.getMessage());
146 public Collection<Class<? extends ThingHandlerService>> getServices() {
147 return Collections.singleton(OpenUVDiscoveryService.class);
150 public @Nullable PointType getLocation() {
151 return locationProvider.getLocation();