]> git.basschouten.com Git - openhab-addons.git/blob
ddf5082a1e06edd301f40b785dd3ee81f89432cf
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2022 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.Optional;
21 import java.util.Properties;
22 import java.util.Set;
23 import java.util.concurrent.ScheduledFuture;
24 import java.util.concurrent.TimeUnit;
25
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;
48
49 import com.google.gson.Gson;
50 import com.google.gson.JsonSyntaxException;
51
52 /**
53  * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
54  * to the webservice.
55  *
56  * @author GaĆ«l L'hopital - Initial contribution
57  *
58  */
59 @NonNullByDefault
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 RECONNECT_DELAY_MIN = 5;
63     private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
64
65     private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
66     private final Properties header = new Properties();
67     private final Gson gson;
68     private final LocationProvider locationProvider;
69     private final TranslationProvider i18nProvider;
70     private final LocaleProvider localeProvider;
71
72     private Optional<ScheduledFuture<?>> reconnectJob = Optional.empty();
73     private boolean keyVerified;
74
75     public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
76             LocaleProvider localeProvider, Gson gson) {
77         super(bridge);
78         this.gson = gson;
79         this.locationProvider = locationProvider;
80         this.i18nProvider = i18nProvider;
81         this.localeProvider = localeProvider;
82     }
83
84     @Override
85     public void initialize() {
86         logger.debug("Initializing OpenUV API bridge handler.");
87         keyVerified = false;
88         BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
89         if (config.apikey.isEmpty()) {
90             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
91                     "@text/offline.config-error-unknown-apikey");
92             return;
93         }
94         header.put("x-access-token", config.apikey);
95         initiateConnexion();
96     }
97
98     @Override
99     public void dispose() {
100         freeReconnectJob();
101     }
102
103     @Override
104     public void handleCommand(ChannelUID channelUID, Command command) {
105         if (command instanceof RefreshType) {
106             initiateConnexion();
107             return;
108         }
109         logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
110     }
111
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");
115     }
116
117     public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
118         String statusMessage = "";
119         ThingStatusDetail statusDetail = ThingStatusDetail.COMMUNICATION_ERROR;
120         String url = String.format(QUERY_URL, latitude, longitude, altitude);
121         String jsonData = "";
122         try {
123             jsonData = HttpUtil.executeUrl("GET", url, header, null, null, REQUEST_TIMEOUT_MS);
124             OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
125             if (uvResponse != null) {
126                 String error = uvResponse.getError();
127                 if (error == null) {
128                     updateStatus(ThingStatus.ONLINE);
129                     keyVerified = true;
130                     return uvResponse.getResult();
131                 }
132                 throw new OpenUVException(error);
133             }
134         } catch (JsonSyntaxException e) {
135             if (jsonData.contains("MongoError")) {
136                 statusMessage = String.format("@text/offline.comm-error-faultly-service [ \"%d\" ]",
137                         RECONNECT_DELAY_MIN);
138                 scheduleReconnectJob(RECONNECT_DELAY_MIN);
139             } else {
140                 statusDetail = ThingStatusDetail.NONE;
141                 statusMessage = String.format("@text/offline.invalid-json [ \"%s\" ]", url);
142                 logger.debug("{} : {}", statusMessage, jsonData);
143             }
144         } catch (IOException e) {
145             statusMessage = e.getMessage();
146         } catch (OpenUVException e) {
147             if (e.isQuotaError()) {
148                 LocalDateTime nextMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
149                 statusMessage = String.format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]",
150                         nextMidnight.toString());
151                 scheduleReconnectJob(Duration.between(LocalDateTime.now(), nextMidnight).toMinutes());
152             } else if (e.isApiKeyError()) {
153                 if (keyVerified) {
154                     statusMessage = String.format("@text/offline.api-key-not-recognized [ \"%d\" ]",
155                             RECONNECT_DELAY_MIN);
156                     scheduleReconnectJob(RECONNECT_DELAY_MIN);
157                 } else {
158                     statusDetail = ThingStatusDetail.CONFIGURATION_ERROR;
159                 }
160             }
161         }
162         updateStatus(ThingStatus.OFFLINE, statusDetail, statusMessage);
163         return null;
164     }
165
166     private void scheduleReconnectJob(long delay) {
167         freeReconnectJob();
168         reconnectJob = Optional.of(scheduler.schedule(this::initiateConnexion, delay, TimeUnit.MINUTES));
169     }
170
171     private void freeReconnectJob() {
172         reconnectJob.ifPresent(job -> job.cancel(true));
173         reconnectJob = Optional.empty();
174     }
175
176     @Override
177     public Collection<Class<? extends ThingHandlerService>> getServices() {
178         return Set.of(OpenUVDiscoveryService.class);
179     }
180
181     public @Nullable PointType getLocation() {
182         return locationProvider.getLocation();
183     }
184
185     public TranslationProvider getI18nProvider() {
186         return i18nProvider;
187     }
188
189     public LocaleProvider getLocaleProvider() {
190         return localeProvider;
191     }
192 }