2 * Copyright (c) 2010-2023 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 an 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 an 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 URL to get or put a service state.
113 * https://localhost:8444/smarthome/devices/hdm:ZigBee:000d6f0016d1cdae/services/AirQualityLevel/state
116 * see https://apidocs.bosch-smarthome.com/local/index.html
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
122 public String getServiceStateUrl(String serviceName, String deviceId) {
123 return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s/state", deviceId, serviceName));
127 * Returns a URL to get general information about a service.
132 * https://localhost:8444/smarthome/devices/hdm:ZigBee:000d6f0016d1cdae/services/BatteryLevel
135 * In some cases this URL has to be used to get the service state, for example for battery levels.
137 * @param serviceName the name of the service
138 * @param deviceId the device identifier
139 * @return a URL to retrieve general service information
141 public String getServiceUrl(String serviceName, String deviceId) {
142 return this.getBoschSmartHomeUrl(String.format("devices/%s/services/%s", deviceId, serviceName));
146 * Checks if the Bosch SHC is online.
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
151 * Will return true, if the server responds with the "public information".
154 * @return true if HTTP server is online
155 * @throws InterruptedException in case of an interrupt
157 public boolean isOnline() throws InterruptedException {
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());
168 logger.debug("Online check failed with status code: {}", contentResponse.getStatus());
171 } catch (TimeoutException | ExecutionException | NullPointerException e) {
172 logger.debug("Online check failed because of {}!", e.getMessage());
178 * Checks if the Bosch SHC can be accessed.
180 * @return true if HTTP access to SHC devices was successful
181 * @throws InterruptedException in case of an interrupt
183 public boolean isAccessPossible() throws InterruptedException {
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());
194 logger.debug("Access check failed with status code: {}", contentResponse.getStatus());
197 } catch (TimeoutException | ExecutionException | NullPointerException e) {
198 logger.debug("Access check failed because of {}!", e.getMessage());
204 * Pairs this client with the Bosch SHC.
205 * Press pairing button on the Bosch Smart Home Controller!
207 * @return true if pairing was successful, otherwise false
208 * @throws InterruptedException in case of an interrupt
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");
214 ContentResponse contentResponse;
216 String publicCert = getCertFromSslContextFactory();
217 logger.trace("Pairing with SHC {}", ipAddress);
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-----");
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)));
232 contentResponse = request.send();
234 logger.trace("Pairing response complete: {} - return code: {}", contentResponse.getContentAsString(),
235 contentResponse.getStatus());
236 if (201 == contentResponse.getStatus()) {
237 logger.debug("Pairing successful.");
240 logger.info("Pairing failed with response status {}.", contentResponse.getStatus());
243 } catch (TimeoutException | CertificateEncodingException | KeyStoreException | NullPointerException e) {
244 logger.warn("Pairing failed with exception {}", e.getMessage());
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?");
256 * Creates a HTTP request.
258 * @param url for the HTTP request
259 * @param method for the HTTP request
260 * @return created HTTP request instance
262 public Request createRequest(String url, HttpMethod method) {
263 return this.createRequest(url, method, null);
267 * Creates a HTTP request.
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
274 public Request createRequest(String url, HttpMethod method, @Nullable Object content) {
275 logger.trace("Create request for http client {}", this.toString());
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
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));
286 logger.trace("create request for {}", url);
293 * Sends a request and expects a response of the specified type.
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
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());
310 ContentResponse contentResponse = request.send();
312 String textContent = contentResponse.getContentAsString();
314 Integer statusCode = contentResponse.getStatus();
315 if (!HttpStatus.getCode(statusCode).isSuccess()) {
316 if (errorResponseHandler != null) {
317 throw errorResponseHandler.apply(statusCode, textContent);
319 throw new ExecutionException(String.format("Request failed with status code %s", statusCode), null);
323 logger.debug("Received response: {} - status: {}", textContent, statusCode);
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);
332 if (!contentValidator.test(content)) {
333 throw new ExecutionException(String.format("Received invalid content for type %s: %s",
334 responseContentClass.getName(), content), null);
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);
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());