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.boschshc.internal.devices.bridge;
15 import static org.eclipse.jetty.http.HttpMethod.GET;
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;
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;
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;
43 import com.google.gson.Gson;
44 import com.google.gson.JsonSyntaxException;
47 * HTTP client using own context with private & Bosch Certs
48 * to pair and connect to the Bosch Smart Home Controller.
50 * @author Gerd Zanker - Initial contribution
53 public class BoschHttpClient extends HttpClient {
54 private static final Gson GSON = new Gson();
56 private final Logger logger = LoggerFactory.getLogger(BoschHttpClient.class);
58 private final String ipAddress;
59 private final String systemPassword;
61 public BoschHttpClient(String ipAddress, String systemPassword, SslContextFactory sslContextFactory) {
62 super(sslContextFactory);
63 this.ipAddress = ipAddress;
64 this.systemPassword = systemPassword;
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
71 * @return URL for public information
73 public String getPublicInformationUrl() {
74 return String.format("https://%s:8446/smarthome/public/information", this.ipAddress);
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
81 * @return URL for pairing
83 public String getPairingUrl() {
84 return String.format("https://%s:8443/smarthome/clients", this.ipAddress);
88 * Returns a Bosch SHC URL for the endpoint, using port 8444.
90 * @param endpoint a endpoint, see https://apidocs.bosch-smarthome.com/local/index.html
91 * @return Bosch SHC URL for passed endpoint
93 public String getBoschShcUrl(String endpoint) {
94 return String.format("https://%s:8444/%s", this.ipAddress, endpoint);
98 * Returns a SmartHome URL for the endpoint - shortcut of {@link BoschSslUtil::getBoschShcUrl()}
100 * @param endpoint a endpoint, see https://apidocs.bosch-smarthome.com/local/index.html
101 * @return SmartHome URL for passed endpoint
103 public String getBoschSmartHomeUrl(String endpoint) {
104 return this.getBoschShcUrl(String.format("smarthome/%s", endpoint));
108 * Returns a device & service URL.
109 * see https://apidocs.bosch-smarthome.com/local/index.html
111 * @param serviceName the name of the service
112 * @param deviceId the device identifier
113 * @return SmartHome URL for passed endpoint
115 public String getServiceUrl(String serviceName, String deviceId) {
116 return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s/state", deviceId, serviceName));
120 * Checks if the Bosch SHC is online.
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
125 * Will return true, if the server responds with the "public information".
128 * @return true if HTTP server is online
129 * @throws InterruptedException in case of an interrupt
131 public boolean isOnline() throws InterruptedException {
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());
142 logger.debug("Online check failed with status code: {}", contentResponse.getStatus());
145 } catch (TimeoutException | ExecutionException | NullPointerException e) {
146 logger.debug("Online check failed because of {}!", e.getMessage());
152 * Checks if the Bosch SHC can be accessed.
154 * @return true if HTTP access to SHC devices was successful
155 * @throws InterruptedException in case of an interrupt
157 public boolean isAccessPossible() throws InterruptedException {
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());
168 logger.debug("Access check failed with status code: {}", contentResponse.getStatus());
171 } catch (TimeoutException | ExecutionException | NullPointerException e) {
172 logger.debug("Access check failed because of {}!", e.getMessage());
178 * Pairs this client with the Bosch SHC.
179 * Press pairing button on the Bosch Smart Home Controller!
181 * @return true if pairing was successful, otherwise false
182 * @throws InterruptedException in case of an interrupt
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");
188 ContentResponse contentResponse;
190 String publicCert = getCertFromSslContextFactory();
191 logger.trace("Pairing with SHC {}", ipAddress);
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-----");
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)));
206 contentResponse = request.send();
208 logger.trace("Pairing response complete: {} - return code: {}", contentResponse.getContentAsString(),
209 contentResponse.getStatus());
210 if (201 == contentResponse.getStatus()) {
211 logger.debug("Pairing successful.");
214 logger.info("Pairing failed with response status {}.", contentResponse.getStatus());
217 } catch (TimeoutException | CertificateEncodingException | KeyStoreException | NullPointerException e) {
218 logger.warn("Pairing failed with exception {}", e.getMessage());
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?");
230 * Creates a HTTP request.
232 * @param url for the HTTP request
233 * @param method for the HTTP request
234 * @return created HTTP request instance
236 public Request createRequest(String url, HttpMethod method) {
237 return this.createRequest(url, method, null);
241 * Creates a HTTP request.
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
248 public Request createRequest(String url, HttpMethod method, @Nullable Object content) {
249 logger.trace("Create request for http client {}", this.toString());
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
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));
260 logger.trace("create request for {}", url);
267 * Sends a request and expects a response of the specified type.
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
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());
284 ContentResponse contentResponse = request.send();
286 String textContent = contentResponse.getContentAsString();
288 Integer statusCode = contentResponse.getStatus();
289 if (!HttpStatus.getCode(statusCode).isSuccess()) {
290 if (errorResponseHandler != null) {
291 throw errorResponseHandler.apply(statusCode, textContent);
293 throw new ExecutionException(String.format("Request failed with status code %s", statusCode), null);
297 logger.debug("Received response: {} - status: {}", textContent, statusCode);
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);
306 if (!contentValidator.test(content)) {
307 throw new ExecutionException(String.format("Received invalid content for type %s: %s",
308 responseContentClass.getName(), content), null);
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);
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());