]> git.basschouten.com Git - openhab-addons.git/blob
17e267baeedb339b3f22a9ce64fc398d66457b81
[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 REQUEST_TIMEOUT_MS = (int) TimeUnit.SECONDS.toMillis(30);
63
64     private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
65     private final Properties header = new Properties();
66     private final Gson gson;
67     private final LocationProvider locationProvider;
68     private final TranslationProvider i18nProvider;
69     private final LocaleProvider localeProvider;
70
71     private Optional<ScheduledFuture<?>> reconnectJob = Optional.empty();
72
73     public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
74             LocaleProvider localeProvider, Gson gson) {
75         super(bridge);
76         this.gson = gson;
77         this.locationProvider = locationProvider;
78         this.i18nProvider = i18nProvider;
79         this.localeProvider = localeProvider;
80     }
81
82     @Override
83     public void initialize() {
84         logger.debug("Initializing OpenUV API bridge handler.");
85         BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
86         if (config.apikey.isEmpty()) {
87             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
88                     "@text/offline.config-error-unknown-apikey");
89             return;
90         }
91         header.put("x-access-token", config.apikey);
92         initiateConnexion();
93     }
94
95     @Override
96     public void dispose() {
97         reconnectJob.ifPresent(job -> job.cancel(true));
98         reconnectJob = Optional.empty();
99     }
100
101     @Override
102     public void handleCommand(ChannelUID channelUID, Command command) {
103         if (command instanceof RefreshType) {
104             initiateConnexion();
105             return;
106         }
107         logger.debug("The OpenUV bridge only handles Refresh command and not '{}'", command);
108     }
109
110     private void initiateConnexion() {
111         // Just checking if the provided api key is a valid one by making a fake call
112         getUVData("0", "0", "0");
113     }
114
115     public @Nullable OpenUVResult getUVData(String latitude, String longitude, String altitude) {
116         String url = String.format(QUERY_URL, latitude, longitude, altitude);
117         String jsonData = "";
118         try {
119             jsonData = HttpUtil.executeUrl("GET", url, 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 (JsonSyntaxException e) {
130             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
131                     String.format("Invalid json received when calling `%s` : %s", url, jsonData));
132         } catch (IOException e) {
133             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
134         } catch (OpenUVException e) {
135             if (e.isQuotaError()) {
136                 LocalDateTime tomorrowMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
137
138                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
139                         .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
140
141                 reconnectJob = Optional.of(scheduler.schedule(this::initiateConnexion,
142                         Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES));
143             } else {
144                 updateStatus(ThingStatus.OFFLINE,
145                         e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
146                         e.getMessage());
147             }
148         }
149         return null;
150     }
151
152     @Override
153     public Collection<Class<? extends ThingHandlerService>> getServices() {
154         return Set.of(OpenUVDiscoveryService.class);
155     }
156
157     public @Nullable PointType getLocation() {
158         return locationProvider.getLocation();
159     }
160
161     public TranslationProvider getI18nProvider() {
162         return i18nProvider;
163     }
164
165     public LocaleProvider getLocaleProvider() {
166         return localeProvider;
167     }
168 }