]> git.basschouten.com Git - openhab-addons.git/blob
b3fb8a1614ccef5ebf555db58ef85e267b3a1a85
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.openuv.internal.handler;
14
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;
24
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;
45
46 import com.google.gson.Gson;
47
48 /**
49  * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
50  * to the webservice.
51  *
52  * @author GaĆ«l L'hopital - Initial contribution
53  *
54  */
55 @NonNullByDefault
56 public class OpenUVBridgeHandler extends BaseBridgeHandler {
57     private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
58
59     private static final String QUERY_URL = "https://api.openuv.io/api/v1/uv?lat=%s&lng=%s&alt=%s";
60
61     private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
62
63     private final Properties header = new Properties();
64     private final Gson gson;
65
66     private final LocationProvider locationProvider;
67     private @Nullable ScheduledFuture<?> reconnectJob;
68
69     public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, Gson gson) {
70         super(bridge);
71         this.gson = gson;
72         this.locationProvider = locationProvider;
73     }
74
75     @Override
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.");
82         } else {
83             header.put("x-access-token", config.apikey);
84             initiateConnexion();
85         }
86     }
87
88     @Override
89     public void dispose() {
90         ScheduledFuture<?> job = this.reconnectJob;
91         if (job != null && !job.isCancelled()) {
92             job.cancel(true);
93         }
94         reconnectJob = null;
95     }
96
97     @Override
98     public void handleCommand(ChannelUID channelUID, Command command) {
99         if (command instanceof RefreshType) {
100             initiateConnexion();
101         } else {
102             logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
103         }
104     }
105
106     private void initiateConnexion() {
107         // Check if the provided api key is valid for use with the OpenUV service
108         getUVData("0", "0", "0");
109     }
110
111     public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
112         try {
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();
119             } else {
120                 throw new OpenUVException(uvResponse.getError());
121             }
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);
129
130                 String message = "Quota Exceeded, going OFFLINE for today, will retry at : "
131                         + tomorrowMidnight.toString();
132                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, message);
133
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());
138             } else {
139                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, e.getMessage());
140             }
141         }
142         return null;
143     }
144
145     @Override
146     public Collection<Class<? extends ThingHandlerService>> getServices() {
147         return Collections.singleton(OpenUVDiscoveryService.class);
148     }
149
150     public @Nullable PointType getLocation() {
151         return locationProvider.getLocation();
152     }
153 }