]> git.basschouten.com Git - openhab-addons.git/blob
211481a7b6613f1fbd20a43843caade1c4861ac1
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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 an 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 an 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 URL to get or put a service state.
109      * <p>
110      * Example:
111      *
112      * <pre>
113      * https://localhost:8444/smarthome/devices/hdm:ZigBee:000d6f0016d1cdae/services/AirQualityLevel/state
114      * </pre>
115      *
116      * see https://apidocs.bosch-smarthome.com/local/index.html
117      *
118      * @param serviceName the name of the service
119      * @param deviceId the device identifier
120      * @return a URL to get or put a service state
121      */
122     public String getServiceStateUrl(String serviceName, String deviceId) {
123         return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s/state", deviceId, serviceName));
124     }
125
126     /**
127      * Returns a URL to get general information about a service.
128      * <p>
129      * Example:
130      *
131      * <pre>
132      * https://localhost:8444/smarthome/devices/hdm:ZigBee:000d6f0016d1cdae/services/BatteryLevel
133      * </pre>
134      *
135      * In some cases this URL has to be used to get the service state, for example for battery levels.
136      *
137      * @param serviceName the name of the service
138      * @param deviceId the device identifier
139      * @return a URL to retrieve general service information
140      */
141     public String getServiceUrl(String serviceName, String deviceId) {
142         return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s", deviceId, serviceName));
143     }
144
145     /**
146      * Checks if the Bosch SHC is online.
147      *
148      * The HTTP server could be offline (Timeout of request).
149      * Or during boot-up the server can response e.g. with SERVICE_UNAVAILABLE_503
150      *
151      * Will return true, if the server responds with the "public information".
152      *
153      *
154      * @return true if HTTP server is online
155      * @throws InterruptedException in case of an interrupt
156      */
157     public boolean isOnline() throws InterruptedException {
158         try {
159             String url = this.getPublicInformationUrl();
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("Online check completed with success: {} - status code: {}", content,
165                         contentResponse.getStatus());
166                 return true;
167             } else {
168                 logger.debug("Online check failed with status code: {}", contentResponse.getStatus());
169                 return false;
170             }
171         } catch (TimeoutException | ExecutionException | NullPointerException e) {
172             logger.debug("Online check failed because of {}!", e.getMessage());
173             return false;
174         }
175     }
176
177     /**
178      * Checks if the Bosch SHC can be accessed.
179      *
180      * @return true if HTTP access to SHC devices was successful
181      * @throws InterruptedException in case of an interrupt
182      */
183     public boolean isAccessPossible() throws InterruptedException {
184         try {
185             String url = this.getBoschSmartHomeUrl("devices");
186             Request request = this.createRequest(url, GET);
187             ContentResponse contentResponse = request.send();
188             if (HttpStatus.getCode(contentResponse.getStatus()).isSuccess()) {
189                 String content = contentResponse.getContentAsString();
190                 logger.debug("Access check completed with success: {} - status code: {}", content,
191                         contentResponse.getStatus());
192                 return true;
193             } else {
194                 logger.debug("Access check failed with status code: {}", contentResponse.getStatus());
195                 return false;
196             }
197         } catch (TimeoutException | ExecutionException | NullPointerException e) {
198             logger.debug("Access check failed because of {}!", e.getMessage());
199             return false;
200         }
201     }
202
203     /**
204      * Pairs this client with the Bosch SHC.
205      * Press pairing button on the Bosch Smart Home Controller!
206      *
207      * @return true if pairing was successful, otherwise false
208      * @throws InterruptedException in case of an interrupt
209      */
210     public boolean doPairing() throws InterruptedException {
211         logger.trace("Starting pairing openHAB Client with Bosch Smart Home Controller!");
212         logger.trace("Please press the Bosch Smart Home Controller button until LED starts blinking");
213
214         ContentResponse contentResponse;
215         try {
216             String publicCert = getCertFromSslContextFactory();
217             logger.trace("Pairing with SHC {}", ipAddress);
218
219             // JSON Rest content
220             Map<String, String> items = new HashMap<>();
221             items.put("@type", "client");
222             items.put("id", BoschSslUtil.getBoschShcClientId()); // Client Id contains the unique OpenHab instance Id
223             items.put("name", "oss_OpenHAB_Binding"); // Client name according to
224                                                       // https://github.com/BoschSmartHome/bosch-shc-api-docs#terms-and-conditions
225             items.put("primaryRole", "ROLE_RESTRICTED_CLIENT");
226             items.put("certificate", "-----BEGIN CERTIFICATE-----\r" + publicCert + "\r-----END CERTIFICATE-----");
227
228             String url = this.getPairingUrl();
229             Request request = this.createRequest(url, HttpMethod.POST, items).header("Systempassword",
230                     Base64.getEncoder().encodeToString(this.systemPassword.getBytes(StandardCharsets.UTF_8)));
231
232             contentResponse = request.send();
233
234             logger.trace("Pairing response complete: {} - return code: {}", contentResponse.getContentAsString(),
235                     contentResponse.getStatus());
236             if (201 == contentResponse.getStatus()) {
237                 logger.debug("Pairing successful.");
238                 return true;
239             } else {
240                 logger.info("Pairing failed with response status {}.", contentResponse.getStatus());
241                 return false;
242             }
243         } catch (TimeoutException | CertificateEncodingException | KeyStoreException | NullPointerException e) {
244             logger.warn("Pairing failed with exception {}", e.getMessage());
245             return false;
246         } catch (ExecutionException e) {
247             // javax.net.ssl.SSLHandshakeException: General SSLEngine problem
248             // => usually the pairing failed, because hardware button was not pressed.
249             logger.trace("Pairing failed - Details: {}", e.getMessage());
250             logger.warn("Pairing failed. Was the Bosch Smart Home Controller button pressed?");
251             return false;
252         }
253     }
254
255     /**
256      * Creates a HTTP request.
257      *
258      * @param url for the HTTP request
259      * @param method for the HTTP request
260      * @return created HTTP request instance
261      */
262     public Request createRequest(String url, HttpMethod method) {
263         return this.createRequest(url, method, null);
264     }
265
266     /**
267      * Creates a HTTP request.
268      *
269      * @param url for the HTTP request
270      * @param method for the HTTP request
271      * @param content for the HTTP request
272      * @return created HTTP request instance
273      */
274     public Request createRequest(String url, HttpMethod method, @Nullable Object content) {
275         logger.trace("Create request for http client {}", this.toString());
276
277         Request request = this.newRequest(url).method(method).header("Content-Type", "application/json")
278                 .header("api-version", "2.1") // see https://github.com/BoschSmartHome/bosch-shc-api-docs/issues/46
279                 .timeout(10, TimeUnit.SECONDS); // Set default timeout
280
281         if (content != null) {
282             String body = GSON.toJson(content);
283             logger.trace("create request for {} and content {}", url, content.toString());
284             request = request.content(new StringContentProvider(body));
285         } else {
286             logger.trace("create request for {}", url);
287         }
288
289         return request;
290     }
291
292     /**
293      * Sends a request and expects a response of the specified type.
294      *
295      * @param request Request to send
296      * @param responseContentClass Type of expected response
297      * @param contentValidator Checks if the parsed response is valid
298      * @param errorResponseHandler Optional ustom error response handling. If not provided a generic exception is thrown
299      * @throws ExecutionException in case of invalid HTTP request result
300      * @throws TimeoutException in case of an HTTP request timeout
301      * @throws InterruptedException in case of an interrupt
302      * @throws BoschSHCException in case of a custom handled error response
303      */
304     public <TContent> TContent sendRequest(Request request, Class<TContent> responseContentClass,
305             Predicate<TContent> contentValidator,
306             @Nullable BiFunction<Integer, String, BoschSHCException> errorResponseHandler)
307             throws InterruptedException, TimeoutException, ExecutionException, BoschSHCException {
308         logger.trace("Send request: {}", request.toString());
309
310         ContentResponse contentResponse = request.send();
311
312         String textContent = contentResponse.getContentAsString();
313
314         Integer statusCode = contentResponse.getStatus();
315         if (!HttpStatus.getCode(statusCode).isSuccess()) {
316             if (errorResponseHandler != null) {
317                 throw errorResponseHandler.apply(statusCode, textContent);
318             } else {
319                 throw new ExecutionException(String.format("Request failed with status code %s", statusCode), null);
320             }
321         }
322
323         logger.debug("Received response: {} - status: {}", textContent, statusCode);
324
325         try {
326             @Nullable
327             TContent content = GSON.fromJson(textContent, responseContentClass);
328             if (content == null) {
329                 throw new ExecutionException(String.format("Received no content in response, expected type %s",
330                         responseContentClass.getName()), null);
331             }
332             if (!contentValidator.test(content)) {
333                 throw new ExecutionException(String.format("Received invalid content for type %s: %s",
334                         responseContentClass.getName(), content), null);
335             }
336             return content;
337         } catch (JsonSyntaxException e) {
338             throw new ExecutionException(String.format("Received invalid content in response, expected type %s: %s",
339                     responseContentClass.getName(), e.getMessage()), e);
340         }
341     }
342
343     private String getCertFromSslContextFactory() throws KeyStoreException, CertificateEncodingException {
344         Certificate cert = this.getSslContextFactory().getKeyStore()
345                 .getCertificate(BoschSslUtil.getBoschShcServerId(ipAddress));
346         return Base64.getEncoder().encodeToString(cert.getEncoded());
347     }
348 }