]> git.basschouten.com Git - openhab-addons.git/blob
1bc9a8fb7f4e008f5a48eecf61f5680d3f851b83
[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.shelly.internal.api;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.SHELLY_API_TIMEOUT_MS;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
19 import java.nio.charset.StandardCharsets;
20 import java.util.Base64;
21 import java.util.Map;
22 import java.util.concurrent.ExecutionException;
23 import java.util.concurrent.TimeUnit;
24 import java.util.concurrent.TimeoutException;
25
26 import org.eclipse.jdt.annotation.NonNullByDefault;
27 import org.eclipse.jetty.client.HttpClient;
28 import org.eclipse.jetty.client.api.ContentResponse;
29 import org.eclipse.jetty.client.api.Request;
30 import org.eclipse.jetty.client.util.StringContentProvider;
31 import org.eclipse.jetty.http.HttpFields;
32 import org.eclipse.jetty.http.HttpHeader;
33 import org.eclipse.jetty.http.HttpMethod;
34 import org.eclipse.jetty.http.HttpStatus;
35 import org.openhab.binding.shelly.internal.config.ShellyThingConfiguration;
36 import org.openhab.binding.shelly.internal.handler.ShellyThingInterface;
37 import org.slf4j.Logger;
38 import org.slf4j.LoggerFactory;
39
40 import com.google.gson.Gson;
41
42 /**
43  * {@link ShellyHttpClient} implements basic HTTP access
44  *
45  * @author Markus Michels - Initial contribution
46  */
47 @NonNullByDefault
48 public class ShellyHttpClient {
49     private final Logger logger = LoggerFactory.getLogger(ShellyHttpClient.class);
50
51     public static final String HTTP_HEADER_AUTH = "Authorization";
52     public static final String HTTP_AUTH_TYPE_BASIC = "Basic";
53     public static final String CONTENT_TYPE_JSON = "application/json; charset=UTF-8";
54     public static final String CONTENT_TYPE_FORM_URLENC = "application/x-www-form-urlencoded";
55
56     protected final HttpClient httpClient;
57     protected ShellyThingConfiguration config = new ShellyThingConfiguration();
58     protected String thingName;
59     protected final Gson gson = new Gson();
60     protected int timeoutErrors = 0;
61     protected int timeoutsRecovered = 0;
62     private ShellyDeviceProfile profile;
63
64     public ShellyHttpClient(String thingName, ShellyThingInterface thing) {
65         this(thingName, thing.getThingConfig(), thing.getHttpClient());
66         this.profile = thing.getProfile();
67         profile.initFromThingType(thingName);
68     }
69
70     public ShellyHttpClient(String thingName, ShellyThingConfiguration config, HttpClient httpClient) {
71         profile = new ShellyDeviceProfile();
72         this.thingName = thingName;
73         setConfig(thingName, config);
74         this.httpClient = httpClient;
75     }
76
77     public void initialize() throws ShellyApiException {
78     }
79
80     public void setConfig(String thingName, ShellyThingConfiguration config) {
81         this.thingName = thingName;
82         this.config = config;
83     }
84
85     /**
86      * Submit GET request and return response, check for invalid responses
87      *
88      * @param uri: URI (e.g. "/settings")
89      */
90     public <T> T callApi(String uri, Class<T> classOfT) throws ShellyApiException {
91         String json = httpRequest(uri);
92         return fromJson(gson, json, classOfT);
93     }
94
95     public <T> T postApi(String uri, String data, Class<T> classOfT) throws ShellyApiException {
96         String json = httpPost(uri, data);
97         return fromJson(gson, json, classOfT);
98     }
99
100     protected String httpRequest(String uri) throws ShellyApiException {
101         ShellyApiResult apiResult = new ShellyApiResult();
102         int retries = 3;
103         boolean timeout = false;
104         while (retries > 0) {
105             try {
106                 apiResult = innerRequest(HttpMethod.GET, uri, "");
107                 if (timeout) {
108                     logger.debug("{}: API timeout #{}/{} recovered ({})", thingName, timeoutErrors, timeoutsRecovered,
109                             apiResult.getUrl());
110                     timeoutsRecovered++;
111                 }
112                 return apiResult.response; // successful
113             } catch (ShellyApiException e) {
114                 if ((!e.isTimeout() && !apiResult.isHttpServerError()) && !apiResult.isNotFound() || profile.hasBattery
115                         || (retries == 0)) {
116                     // Sensor in sleep mode or API exception for non-battery device or retry counter expired
117                     throw e; // non-timeout exception
118                 }
119
120                 timeout = true;
121                 retries--;
122                 timeoutErrors++; // count the retries
123                 logger.debug("{}: API Timeout, retry #{} ({})", thingName, timeoutErrors, e.toString());
124             }
125         }
126         throw new ShellyApiException("API Timeout or inconsistent result"); // successful
127     }
128
129     public String httpPost(String uri, String data) throws ShellyApiException {
130         return innerRequest(HttpMethod.POST, uri, data).response;
131     }
132
133     private ShellyApiResult innerRequest(HttpMethod method, String uri, String data) throws ShellyApiException {
134         Request request = null;
135         String url = "http://" + config.deviceIp + uri;
136         ShellyApiResult apiResult = new ShellyApiResult(method.toString(), url);
137
138         try {
139             request = httpClient.newRequest(url).method(method.toString()).timeout(SHELLY_API_TIMEOUT_MS,
140                     TimeUnit.MILLISECONDS);
141
142             if (!config.password.isEmpty() && !getString(data).contains("\"auth\":{")) {
143                 String value = config.userId + ":" + config.password;
144                 request.header(HTTP_HEADER_AUTH,
145                         HTTP_AUTH_TYPE_BASIC + " " + Base64.getEncoder().encodeToString(value.getBytes()));
146             }
147             fillPostData(request, data);
148             logger.trace("{}: HTTP {} for {} {}", thingName, method, url, data);
149
150             // Do request and get response
151             ContentResponse contentResponse = request.send();
152             apiResult = new ShellyApiResult(contentResponse);
153             apiResult.httpCode = contentResponse.getStatus();
154             String response = contentResponse.getContentAsString().replace("\t", "").replace("\r\n", "").trim();
155             logger.trace("{}: HTTP Response {}: {}", thingName, contentResponse.getStatus(), response);
156
157             HttpFields headers = contentResponse.getHeaders();
158             String auth = headers.get(HttpHeader.WWW_AUTHENTICATE);
159             if (!getString(auth).isEmpty()) {
160                 apiResult.authResponse = auth;
161             }
162
163             // validate response, API errors are reported as Json
164             if (apiResult.httpCode != HttpStatus.OK_200) {
165                 throw new ShellyApiException(apiResult);
166             }
167
168             if (response.isEmpty() || !response.startsWith("{") && !response.startsWith("[") && !url.contains("/debug/")
169                     && !url.contains("/sta_cache_reset")) {
170                 throw new ShellyApiException("Unexpected response: " + response);
171             }
172         } catch (ExecutionException | InterruptedException | TimeoutException | IllegalArgumentException e) {
173             ShellyApiException ex = new ShellyApiException(apiResult, e);
174             if (!ex.isTimeout()) { // will be handled by the caller
175                 logger.trace("{}: API call returned exception", thingName, ex);
176             }
177             throw ex;
178         }
179         return apiResult;
180     }
181
182     /**
183      * Fill in POST data, set http headers
184      *
185      * @param request HTTP request structure
186      * @param data POST data, might be empty
187      */
188     private void fillPostData(Request request, String data) {
189         boolean json = data.startsWith("{") || data.contains("\": {");
190         String type = json ? CONTENT_TYPE_JSON : CONTENT_TYPE_FORM_URLENC;
191         request.header(HttpHeader.CONTENT_TYPE, type);
192         if (!data.isEmpty()) {
193             StringContentProvider postData;
194             postData = new StringContentProvider(type, data, StandardCharsets.UTF_8);
195             request.content(postData);
196             request.header(HttpHeader.CONTENT_LENGTH, Long.toString(postData.getLength()));
197         }
198     }
199
200     /**
201      * Format POST body depending on content type (JSON or form encoded)
202      *
203      * @param dataMap Field list
204      * @param json true=JSON format, false=form encoded
205      * @return formatted body
206      */
207     public static String buildPostData(Map<String, String> dataMap, boolean json) {
208         String data = "";
209         for (Map.Entry<String, String> e : dataMap.entrySet()) {
210             data = data + (data.isEmpty() ? "" : json ? ", " : "&");
211             if (!json) {
212                 data = data + e.getKey() + "=" + e.getValue();
213             } else {
214                 data = data + "\"" + e.getKey() + "\" : \"" + e.getValue() + "\"";
215             }
216         }
217         return json ? "{ " + data + " }" : data;
218     }
219
220     public String getControlUriPrefix(Integer id) {
221         String uri = "";
222         if (profile.isLight || profile.isDimmer) {
223             if (profile.isDuo || profile.isDimmer) {
224                 // Duo + Dimmer
225                 uri = SHELLY_URL_CONTROL_LIGHT;
226             } else {
227                 // Bulb + RGBW2
228                 uri = "/" + (profile.inColor ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
229             }
230         } else {
231             // Roller, Relay
232             uri = SHELLY_URL_CONTROL_RELEAY;
233         }
234         uri = uri + "/" + id;
235         return uri;
236     }
237
238     public int getTimeoutErrors() {
239         return timeoutErrors;
240     }
241
242     public int getTimeoutsRecovered() {
243         return timeoutsRecovered;
244     }
245 }