]> git.basschouten.com Git - openhab-addons.git/blob
b6c7e345578b07587e93e305876cc76d6a0cc3c4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.boschshc.internal.devices.bridge;
14
15 import static org.eclipse.jetty.http.HttpMethod.GET;
16
17 import java.nio.charset.StandardCharsets;
18 import java.security.KeyStoreException;
19 import java.security.cert.Certificate;
20 import java.security.cert.CertificateEncodingException;
21 import java.util.Base64;
22 import java.util.HashMap;
23 import java.util.Map;
24 import java.util.concurrent.ExecutionException;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.TimeoutException;
27 import java.util.function.BiFunction;
28 import java.util.function.Predicate;
29
30 import org.eclipse.jdt.annotation.NonNullByDefault;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.eclipse.jetty.client.HttpClient;
33 import org.eclipse.jetty.client.api.ContentResponse;
34 import org.eclipse.jetty.client.api.Request;
35 import org.eclipse.jetty.client.util.StringContentProvider;
36 import org.eclipse.jetty.http.HttpMethod;
37 import org.eclipse.jetty.http.HttpStatus;
38 import org.eclipse.jetty.util.ssl.SslContextFactory;
39 import org.openhab.binding.boschshc.internal.exceptions.BoschSHCException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import com.google.gson.Gson;
44 import com.google.gson.JsonSyntaxException;
45
46 /**
47  * HTTP client using own context with private & Bosch Certs
48  * to pair and connect to the Bosch Smart Home Controller.
49  *
50  * @author Gerd Zanker - Initial contribution
51  */
52 @NonNullByDefault
53 public class BoschHttpClient extends HttpClient {
54     private static final Gson GSON = new Gson();
55
56     private final Logger logger = LoggerFactory.getLogger(BoschHttpClient.class);
57
58     private final String ipAddress;
59     private final String systemPassword;
60
61     public BoschHttpClient(String ipAddress, String systemPassword, SslContextFactory sslContextFactory) {
62         super(sslContextFactory);
63         this.ipAddress = ipAddress;
64         this.systemPassword = systemPassword;
65     }
66
67     /**
68      * Returns the public information URL for the Bosch SHC clients, using port 8446.
69      * See https://github.com/BoschSmartHome/bosch-shc-api-docs/blob/master/postman/README.md
70      *
71      * @return URL for public information
72      */
73     public String getPublicInformationUrl() {
74         return String.format("https://%s:8446/smarthome/public/information", this.ipAddress);
75     }
76
77     /**
78      * Returns the pairing URL for the Bosch SHC clients, using port 8443.
79      * See https://github.com/BoschSmartHome/bosch-shc-api-docs/blob/master/postman/README.md
80      * 
81      * @return URL for pairing
82      */
83     public String getPairingUrl() {
84         return String.format("https://%s:8443/smarthome/clients", this.ipAddress);
85     }
86
87     /**
88      * Returns a Bosch SHC URL for the endpoint, using port 8444.
89      * 
90      * @param endpoint a endpoint, see https://apidocs.bosch-smarthome.com/local/index.html
91      * @return Bosch SHC URL for passed endpoint
92      */
93     public String getBoschShcUrl(String endpoint) {
94         return String.format("https://%s:8444/%s", this.ipAddress, endpoint);
95     }
96
97     /**
98      * Returns a SmartHome URL for the endpoint - shortcut of {@link BoschSslUtil::getBoschShcUrl()}
99      * 
100      * @param endpoint a endpoint, see https://apidocs.bosch-smarthome.com/local/index.html
101      * @return SmartHome URL for passed endpoint
102      */
103     public String getBoschSmartHomeUrl(String endpoint) {
104         return this.getBoschShcUrl(String.format("smarthome/%s", endpoint));
105     }
106
107     /**
108      * Returns a device & service URL.
109      * see https://apidocs.bosch-smarthome.com/local/index.html
110      * 
111      * @param serviceName the name of the service
112      * @param deviceId the device identifier
113      * @return SmartHome URL for passed endpoint
114      */
115     public String getServiceUrl(String serviceName, String deviceId) {
116         return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s/state", deviceId, serviceName));
117     }
118
119     /**
120      * Checks if the Bosch SHC is online.
121      *
122      * The HTTP server could be offline (Timeout of request).
123      * Or during boot-up the server can response e.g. with SERVICE_UNAVAILABLE_503
124      *
125      * Will return true, if the server responds with the "public information".
126      *
127      *
128      * @return true if HTTP server is online
129      * @throws InterruptedException in case of an interrupt
130      */
131     public boolean isOnline() throws InterruptedException {
132         try {
133             String url = this.getPublicInformationUrl();
134             Request request = this.createRequest(url, GET);
135             ContentResponse contentResponse = request.send();
136             if (HttpStatus.getCode(contentResponse.getStatus()).isSuccess()) {
137                 String content = contentResponse.getContentAsString();
138                 logger.debug("Online check completed with success: {} - status code: {}", content,
139                         contentResponse.getStatus());
140                 return true;
141             } else {
142                 logger.debug("Online check failed with status code: {}", contentResponse.getStatus());
143                 return false;
144             }
145         } catch (TimeoutException | ExecutionException | NullPointerException e) {
146             logger.debug("Online check failed because of {}!", e.getMessage());
147             return false;
148         }
149     }
150
151     /**
152      * Checks if the Bosch SHC can be accessed.
153      *
154      * @return true if HTTP access to SHC devices was successful
155      * @throws InterruptedException in case of an interrupt
156      */
157     public boolean isAccessPossible() throws InterruptedException {
158         try {
159             String url = this.getBoschSmartHomeUrl("devices");
160             Request request = this.createRequest(url, GET);
161             ContentResponse contentResponse = request.send();
162             if (HttpStatus.getCode(contentResponse.getStatus()).isSuccess()) {
163                 String content = contentResponse.getContentAsString();
164                 logger.debug("Access check completed with success: {} - status code: {}", content,
165                         contentResponse.getStatus());
166                 return true;
167             } else {
168                 logger.debug("Access check failed with status code: {}", contentResponse.getStatus());
169                 return false;
170             }
171         } catch (TimeoutException | ExecutionException | NullPointerException e) {
172             logger.debug("Access check failed because of {}!", e.getMessage());
173             return false;
174         }
175     }
176
177     /**
178      * Pairs this client with the Bosch SHC.
179      * Press pairing button on the Bosch Smart Home Controller!
180      * 
181      * @return true if pairing was successful, otherwise false
182      * @throws InterruptedException in case of an interrupt
183      */
184     public boolean doPairing() throws InterruptedException {
185         logger.trace("Starting pairing openHAB Client with Bosch Smart Home Controller!");
186         logger.trace("Please press the Bosch Smart Home Controller button until LED starts blinking");
187
188         ContentResponse contentResponse;
189         try {
190             String publicCert = getCertFromSslContextFactory();
191             logger.trace("Pairing with SHC {}", ipAddress);
192
193             // JSON Rest content
194             Map<String, String> items = new HashMap<>();
195             items.put("@type", "client");
196             items.put("id", BoschSslUtil.getBoschShcClientId()); // Client Id contains the unique OpenHab instance Id
197             items.put("name", "oss_OpenHAB_Binding"); // Client name according to
198                                                       // https://github.com/BoschSmartHome/bosch-shc-api-docs#terms-and-conditions
199             items.put("primaryRole", "ROLE_RESTRICTED_CLIENT");
200             items.put("certificate", "-----BEGIN CERTIFICATE-----\r" + publicCert + "\r-----END CERTIFICATE-----");
201
202             String url = this.getPairingUrl();
203             Request request = this.createRequest(url, HttpMethod.POST, items).header("Systempassword",
204                     Base64.getEncoder().encodeToString(this.systemPassword.getBytes(StandardCharsets.UTF_8)));
205
206             contentResponse = request.send();
207
208             logger.trace("Pairing response complete: {} - return code: {}", contentResponse.getContentAsString(),
209                     contentResponse.getStatus());
210             if (201 == contentResponse.getStatus()) {
211                 logger.debug("Pairing successful.");
212                 return true;
213             } else {
214                 logger.info("Pairing failed with response status {}.", contentResponse.getStatus());
215                 return false;
216             }
217         } catch (TimeoutException | CertificateEncodingException | KeyStoreException | NullPointerException e) {
218             logger.warn("Pairing failed with exception {}", e.getMessage());
219             return false;
220         } catch (ExecutionException e) {
221             // javax.net.ssl.SSLHandshakeException: General SSLEngine problem
222             // => usually the pairing failed, because hardware button was not pressed.
223             logger.trace("Pairing failed - Details: {}", e.getMessage());
224             logger.warn("Pairing failed. Was the Bosch Smart Home Controller button pressed?");
225             return false;
226         }
227     }
228
229     /**
230      * Creates a HTTP request.
231      * 
232      * @param url for the HTTP request
233      * @param method for the HTTP request
234      * @return created HTTP request instance
235      */
236     public Request createRequest(String url, HttpMethod method) {
237         return this.createRequest(url, method, null);
238     }
239
240     /**
241      * Creates a HTTP request.
242      * 
243      * @param url for the HTTP request
244      * @param method for the HTTP request
245      * @param content for the HTTP request
246      * @return created HTTP request instance
247      */
248     public Request createRequest(String url, HttpMethod method, @Nullable Object content) {
249         logger.trace("Create request for http client {}", this.toString());
250
251         Request request = this.newRequest(url).method(method).header("Content-Type", "application/json")
252                 .header("api-version", "2.1") // see https://github.com/BoschSmartHome/bosch-shc-api-docs/issues/46
253                 .timeout(10, TimeUnit.SECONDS); // Set default timeout
254
255         if (content != null) {
256             String body = GSON.toJson(content);
257             logger.trace("create request for {} and content {}", url, content.toString());
258             request = request.content(new StringContentProvider(body));
259         } else {
260             logger.trace("create request for {}", url);
261         }
262
263         return request;
264     }
265
266     /**
267      * Sends a request and expects a response of the specified type.
268      * 
269      * @param request Request to send
270      * @param responseContentClass Type of expected response
271      * @param contentValidator Checks if the parsed response is valid
272      * @param errorResponseHandler Optional ustom error response handling. If not provided a generic exception is thrown
273      * @throws ExecutionException in case of invalid HTTP request result
274      * @throws TimeoutException in case of an HTTP request timeout
275      * @throws InterruptedException in case of an interrupt
276      * @throws BoschSHCException in case of a custom handled error response
277      */
278     public <TContent> TContent sendRequest(Request request, Class<TContent> responseContentClass,
279             Predicate<TContent> contentValidator,
280             @Nullable BiFunction<Integer, String, BoschSHCException> errorResponseHandler)
281             throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
282         logger.trace("Send request: {}", request.toString());
283
284         ContentResponse contentResponse = request.send();
285
286         String textContent = contentResponse.getContentAsString();
287
288         Integer statusCode = contentResponse.getStatus();
289         if (!HttpStatus.getCode(statusCode).isSuccess()) {
290             if (errorResponseHandler != null) {
291                 throw errorResponseHandler.apply(statusCode, textContent);
292             } else {
293                 throw new ExecutionException(String.format("Request failed with status code %s", statusCode), null);
294             }
295         }
296
297         logger.debug("Received response: {} - status: {}", textContent, statusCode);
298
299         try {
300             @Nullable
301             TContent content = GSON.fromJson(textContent, responseContentClass);
302             if (content == null) {
303                 throw new ExecutionException(String.format("Received no content in response, expected type %s",
304                         responseContentClass.getName()), null);
305             }
306             if (!contentValidator.test(content)) {
307                 throw new ExecutionException(String.format("Received invalid content for type %s: %s",
308                         responseContentClass.getName(), content), null);
309             }
310             return content;
311         } catch (JsonSyntaxException e) {
312             throw new ExecutionException(String.format("Received invalid content in response, expected type %s: %s",
313                     responseContentClass.getName(), e.getMessage()), e);
314         }
315     }
316
317     private String getCertFromSslContextFactory() throws KeyStoreException, CertificateEncodingException {
318         Certificate cert = this.getSslContextFactory().getKeyStore()
319                 .getCertificate(BoschSslUtil.getBoschShcServerId(ipAddress));
320         return Base64.getEncoder().encodeToString(cert.getEncoded());
321     }
322 }