2 * Copyright (c) 2010-2022 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
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
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.foobot.internal;
15 import static org.openhab.binding.foobot.internal.FoobotBindingConstants.*;
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;
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;
40 import com.google.gson.Gson;
41 import com.google.gson.JsonParseException;
42 import com.google.gson.reflect.TypeToken;
45 * Connector class communicating with Foobot api and parsing returned json.
47 * @author Hilbrand Bouwkamp - Initial contribution
50 public class FoobotApiConnector {
52 public static final String API_RATE_LIMIT_EXCEEDED_MESSAGE = "Api rate limit exceeded";
53 public static final int API_RATE_LIMIT_EXCEEDED = -2;
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>>() {
63 private final Logger logger = LoggerFactory.getLogger(FoobotApiConnector.class);
65 private @Nullable HttpClient httpClient;
66 private String apiKey = "";
67 private int apiKeyLimitRemaining = UNKNOWN_REMAINING;
69 public void setHttpClient(@Nullable HttpClient httpClient) {
70 this.httpClient = httpClient;
73 public void setApiKey(String apiKey) {
78 * @return Returns the last known api remaining limit or -1 if not known.
80 public int getApiKeyLimitRemaining() {
81 return apiKeyLimitRemaining;
85 * Retrieves the list of associated devices with the given username from the foobot api.
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
91 public synchronized List<FoobotDevice> getAssociatedDevices(String username) throws FoobotApiException {
93 final String url = URL_TO_FETCH_DEVICES.replace("%username%",
94 URLEncoder.encode(username, StandardCharsets.UTF_8));
95 logger.debug("URL = {}", url);
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());
105 * Retrieves the sensor data for the device with the given uuid from the foobot api.
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
111 public synchronized @Nullable FoobotJsonData getSensorData(String uuid) throws FoobotApiException {
113 final String url = URL_TO_FETCH_SENSOR_DATA.replace("%uuid%",
114 URLEncoder.encode(uuid, StandardCharsets.UTF_8));
115 logger.debug("URL = {}", url);
117 return GSON.fromJson(request(url, apiKey), FoobotJsonData.class);
118 } catch (JsonParseException e) {
119 throw new FoobotApiException(0, e.getMessage());
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");
129 final Request request = httpClient.newRequest(url).timeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS);
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;
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());
144 final String content = response.getContentAsString();
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");
162 logger.trace("Foobot returned status '{}', reason: {}, content = {}", response.getStatus(),
163 response.getReason(), content);
164 throw new FoobotApiException(response.getStatus(), response.getReason());
168 private void setApiKeyLimitRemaining(ContentResponse response) {
169 final HttpField field = response.getHeaders().getField(HEADER_X_API_KEY_LIMIT_REMAINING);
172 apiKeyLimitRemaining = field.getIntValue();