]> git.basschouten.com Git - openhab-addons.git/blob
9bedc5dfa6f876fff57387976f9c35b410ce1431
[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.foobot.internal;
14
15 import static org.openhab.binding.foobot.internal.FoobotBindingConstants.*;
16
17 import java.lang.reflect.Type;
18 import java.net.URLEncoder;
19 import java.nio.charset.StandardCharsets;
20 import java.util.ArrayList;
21 import java.util.List;
22 import java.util.Objects;
23 import java.util.concurrent.ExecutionException;
24 import java.util.concurrent.TimeUnit;
25 import java.util.concurrent.TimeoutException;
26
27 import org.eclipse.jdt.annotation.NonNullByDefault;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.eclipse.jetty.client.api.ContentResponse;
31 import org.eclipse.jetty.client.api.Request;
32 import org.eclipse.jetty.http.HttpField;
33 import org.eclipse.jetty.http.HttpHeader;
34 import org.eclipse.jetty.http.HttpStatus;
35 import org.openhab.binding.foobot.internal.json.FoobotDevice;
36 import org.openhab.binding.foobot.internal.json.FoobotJsonData;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.gson.Gson;
41 import com.google.gson.JsonParseException;
42 import com.google.gson.reflect.TypeToken;
43
44 /**
45  * Connector class communicating with Foobot api and parsing returned json.
46  *
47  * @author Hilbrand Bouwkamp - Initial contribution
48  */
49 @NonNullByDefault
50 public class FoobotApiConnector {
51
52     public static final String API_RATE_LIMIT_EXCEEDED_MESSAGE = "Api rate limit exceeded";
53     public static final int API_RATE_LIMIT_EXCEEDED = -2;
54
55     private static final int UNKNOWN_REMAINING = -1;
56     private static final String HEADER_X_API_KEY_TOKEN = "X-API-KEY-TOKEN";
57     private static final String HEADER_X_API_KEY_LIMIT_REMAINING = "x-api-key-limit-remaining";
58     private static final int REQUEST_TIMEOUT_SECONDS = 3;
59     private static final Gson GSON = new Gson();
60     private static final Type FOOTBOT_DEVICE_LIST_TYPE = new TypeToken<ArrayList<FoobotDevice>>() {
61     }.getType();
62
63     private final Logger logger = LoggerFactory.getLogger(FoobotApiConnector.class);
64
65     private @Nullable HttpClient httpClient;
66     private String apiKey = "";
67     private int apiKeyLimitRemaining = UNKNOWN_REMAINING;
68
69     public void setHttpClient(@Nullable HttpClient httpClient) {
70         this.httpClient = httpClient;
71     }
72
73     public void setApiKey(String apiKey) {
74         this.apiKey = apiKey;
75     }
76
77     /**
78      * @return Returns the last known api remaining limit or -1 if not known.
79      */
80     public int getApiKeyLimitRemaining() {
81         return apiKeyLimitRemaining;
82     }
83
84     /**
85      * Retrieves the list of associated devices with the given username from the foobot api.
86      *
87      * @param username to get the associated devices for
88      * @return List of devices
89      * @throws FoobotApiException in case there was a problem communicating or parsing the response
90      */
91     public synchronized List<FoobotDevice> getAssociatedDevices(String username) throws FoobotApiException {
92         try {
93             final String url = URL_TO_FETCH_DEVICES.replace("%username%",
94                     URLEncoder.encode(username, StandardCharsets.UTF_8));
95             logger.debug("URL = {}", url);
96
97             List<FoobotDevice> foobotDevices = GSON.fromJson(request(url, apiKey), FOOTBOT_DEVICE_LIST_TYPE);
98             return Objects.requireNonNull(foobotDevices);
99         } catch (JsonParseException e) {
100             throw new FoobotApiException(0, e.getMessage());
101         }
102     }
103
104     /**
105      * Retrieves the sensor data for the device with the given uuid from the foobot api.
106      *
107      * @param uuid of the device to get the sensor data for
108      * @return sensor data of the device
109      * @throws FoobotApiException in case there was a problem communicating or parsing the response
110      */
111     public synchronized @Nullable FoobotJsonData getSensorData(String uuid) throws FoobotApiException {
112         try {
113             final String url = URL_TO_FETCH_SENSOR_DATA.replace("%uuid%",
114                     URLEncoder.encode(uuid, StandardCharsets.UTF_8));
115             logger.debug("URL = {}", url);
116
117             return GSON.fromJson(request(url, apiKey), FoobotJsonData.class);
118         } catch (JsonParseException e) {
119             throw new FoobotApiException(0, e.getMessage());
120         }
121     }
122
123     protected String request(String url, String apiKey) throws FoobotApiException {
124         apiKeyLimitRemaining = UNKNOWN_REMAINING;
125         if (httpClient == null) {
126             logger.debug("No http connection possible: httpClient == null");
127             throw new FoobotApiException(0, "No http connection possible");
128         }
129         final Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
130
131         request.header(HttpHeader.ACCEPT, "application/json");
132         request.header(HttpHeader.ACCEPT_ENCODING, StandardCharsets.UTF_8.name());
133         request.header(HEADER_X_API_KEY_TOKEN, apiKey);
134         final ContentResponse response;
135
136         try {
137             response = request.send();
138         } catch (InterruptedException e) {
139             Thread.currentThread().interrupt();
140             throw new FoobotApiException(0, e.getMessage());
141         } catch (TimeoutException | ExecutionException e) {
142             throw new FoobotApiException(0, e.getMessage());
143         }
144         final String content = response.getContentAsString();
145
146         logger.trace("Foobot content = {}", content);
147         logger.debug("Foobot response = {}", response);
148         setApiKeyLimitRemaining(response);
149         switch (response.getStatus()) {
150             case HttpStatus.FORBIDDEN_403:
151                 throw new FoobotApiException(response.getStatus(),
152                         "Access denied. Did you set the correct api-key and/or username?");
153             case HttpStatus.TOO_MANY_REQUESTS_429:
154                 apiKeyLimitRemaining = API_RATE_LIMIT_EXCEEDED;
155                 throw new FoobotApiException(response.getStatus(), API_RATE_LIMIT_EXCEEDED_MESSAGE);
156             case HttpStatus.OK_200:
157                 if (content == null || content.isBlank()) {
158                     throw new FoobotApiException(0, "No data returned");
159                 }
160                 return content;
161             default:
162                 logger.trace("Foobot returned status '{}', reason: {}, content = {}", response.getStatus(),
163                         response.getReason(), content);
164                 throw new FoobotApiException(response.getStatus(), response.getReason());
165         }
166     }
167
168     private void setApiKeyLimitRemaining(ContentResponse response) {
169         final HttpField field = response.getHeaders().getField(HEADER_X_API_KEY_LIMIT_REMAINING);
170
171         if (field != null) {
172             apiKeyLimitRemaining = field.getIntValue();
173         }
174     }
175 }