]> git.basschouten.com Git - openhab-addons.git/blob
6388e0a287729e1c3d36abb4f0a569607847dfbf
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.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;
47
48 import com.google.gson.Gson;
49
50 /**
51  * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
52  * to the webservice.
53  *
54  * @author GaĆ«l L'hopital - Initial contribution
55  *
56  */
57 @NonNullByDefault
58 public class OpenUVBridgeHandler extends BaseBridgeHandler {
59     private static final String QUERY_URL = "https://api.openuv.io/api/v1/uv?lat=%s&lng=%s&alt=%s";
60     private static final int REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
61
62     private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
63     private final Properties header = new Properties();
64     private final Gson gson;
65     private final LocationProvider locationProvider;
66     private final TranslationProvider i18nProvider;
67     private final LocaleProvider localeProvider;
68
69     private @Nullable ScheduledFuture<?> reconnectJob;
70
71     public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
72             LocaleProvider localeProvider, Gson gson) {
73         super(bridge);
74         this.gson = gson;
75         this.locationProvider = locationProvider;
76         this.i18nProvider = i18nProvider;
77         this.localeProvider = localeProvider;
78     }
79
80     @Override
81     public void initialize() {
82         logger.debug("Initializing OpenUV API bridge handler.");
83         BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
84         if (config.apikey.isEmpty()) {
85             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
86                     "@text/offline.config-error-unknown-apikey");
87             return;
88         }
89         header.put("x-access-token", config.apikey);
90         initiateConnexion();
91     }
92
93     @Override
94     public void dispose() {
95         ScheduledFuture<?> job = this.reconnectJob;
96         if (job != null && !job.isCancelled()) {
97             job.cancel(true);
98         }
99         reconnectJob = null;
100     }
101
102     @Override
103     public void handleCommand(ChannelUID channelUID, Command command) {
104         if (command instanceof RefreshType) {
105             initiateConnexion();
106             return;
107         }
108         logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
109     }
110
111     private void initiateConnexion() {
112         // Just checking if the provided api key is a valid one by making a fake call
113         getUVData("0", "0", "0");
114     }
115
116     public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
117         try {
118             String jsonData = HttpUtil.executeUrl("GET", String.format(QUERY_URL, latitude, longitude, altitude),
119                     header, null, null, REQUEST_TIMEOUT_MS);
120             OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
121             if (uvResponse != null) {
122                 String error = uvResponse.getError();
123                 if (error == null) {
124                     updateStatus(ThingStatus.ONLINE);
125                     return uvResponse.getResult();
126                 }
127                 throw new OpenUVException(error);
128             }
129         } catch (IOException e) {
130             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
131         } catch (OpenUVException e) {
132             if (e.isQuotaError()) {
133                 LocalDate today = LocalDate.now();
134                 LocalDate tomorrow = today.plusDays(1);
135                 LocalDateTime tomorrowMidnight = tomorrow.atStartOfDay().plusMinutes(2);
136
137                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
138                         .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
139
140                 reconnectJob = scheduler.schedule(this::initiateConnexion,
141                         Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);
142             } else {
143                 updateStatus(ThingStatus.OFFLINE,
144                         e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
145                         e.getMessage());
146             }
147         }
148         return null;
149     }
150
151     @Override
152     public Collection<Class<? extends ThingHandlerService>> getServices() {
153         return Collections.singleton(OpenUVDiscoveryService.class);
154     }
155
156     public @Nullable PointType getLocation() {
157         return locationProvider.getLocation();
158     }
159
160     public TranslationProvider getI18nProvider() {
161         return i18nProvider;
162     }
163
164     public LocaleProvider getLocaleProvider() {
165         return localeProvider;
166     }
167 }