]> git.basschouten.com Git - openhab-addons.git/blob
541b53409b599da6bc145b8386d848eec00a83d0
[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.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 import com.google.gson.JsonSyntaxException;
50
51 /**
52  * {@link OpenUVBridgeHandler} is the handler for OpenUV API and connects it
53  * to the webservice.
54  *
55  * @author GaĆ«l L'hopital - Initial contribution
56  *
57  */
58 @NonNullByDefault
59 public class OpenUVBridgeHandler extends BaseBridgeHandler {
60     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);
62
63     private final Logger logger = LoggerFactory.getLogger(OpenUVBridgeHandler.class);
64     private final Properties header = new Properties();
65     private final Gson gson;
66     private final LocationProvider locationProvider;
67     private final TranslationProvider i18nProvider;
68     private final LocaleProvider localeProvider;
69
70     private @Nullable ScheduledFuture<?> reconnectJob;
71
72     public OpenUVBridgeHandler(Bridge bridge, LocationProvider locationProvider, TranslationProvider i18nProvider,
73             LocaleProvider localeProvider, Gson gson) {
74         super(bridge);
75         this.gson = gson;
76         this.locationProvider = locationProvider;
77         this.i18nProvider = i18nProvider;
78         this.localeProvider = localeProvider;
79     }
80
81     @Override
82     public void initialize() {
83         logger.debug("Initializing OpenUV API bridge handler.");
84         BridgeConfiguration config = getConfigAs(BridgeConfiguration.class);
85         if (config.apikey.isEmpty()) {
86             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
87                     "@text/offline.config-error-unknown-apikey");
88             return;
89         }
90         header.put("x-access-token", config.apikey);
91         initiateConnexion();
92     }
93
94     @Override
95     public void dispose() {
96         ScheduledFuture<?> job = this.reconnectJob;
97         if (job != null && !job.isCancelled()) {
98             job.cancel(true);
99         }
100         reconnectJob = null;
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 url = String.format(QUERY_URL, latitude, longitude, altitude);
119         String jsonData = "";
120         try {
121             jsonData = HttpUtil.executeUrl("GET", url, header, null, null, REQUEST_TIMEOUT_MS);
122             OpenUVResponse uvResponse = gson.fromJson(jsonData, OpenUVResponse.class);
123             if (uvResponse != null) {
124                 String error = uvResponse.getError();
125                 if (error == null) {
126                     updateStatus(ThingStatus.ONLINE);
127                     return uvResponse.getResult();
128                 }
129                 throw new OpenUVException(error);
130             }
131         } catch (JsonSyntaxException e) {
132             logger.debug("No valid json received when calling `{}` : {}", url, jsonData);
133         } catch (IOException e) {
134             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
135         } catch (OpenUVException e) {
136             if (e.isQuotaError()) {
137                 LocalDateTime tomorrowMidnight = LocalDate.now().plusDays(1).atStartOfDay().plusMinutes(2);
138
139                 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String
140                         .format("@text/offline.comm-error-quota-exceeded [ \"%s\" ]", tomorrowMidnight.toString()));
141
142                 reconnectJob = scheduler.schedule(this::initiateConnexion,
143                         Duration.between(LocalDateTime.now(), tomorrowMidnight).toMinutes(), TimeUnit.MINUTES);
144             } else {
145                 updateStatus(ThingStatus.OFFLINE,
146                         e.isApiKeyError() ? ThingStatusDetail.CONFIGURATION_ERROR : ThingStatusDetail.NONE,
147                         e.getMessage());
148             }
149         }
150         return null;
151     }
152
153     @Override
154     public Collection<Class<? extends ThingHandlerService>> getServices() {
155         return Collections.singleton(OpenUVDiscoveryService.class);
156     }
157
158     public @Nullable PointType getLocation() {
159         return locationProvider.getLocation();
160     }
161
162     public TranslationProvider getI18nProvider() {
163         return i18nProvider;
164     }
165
166     public LocaleProvider getLocaleProvider() {
167         return localeProvider;
168     }
169 }