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.io.openhabcloud.internal;
15 import java.io.IOException;
16 import java.net.MalformedURLException;
18 import java.net.URISyntaxException;
20 import java.net.URLEncoder;
21 import java.nio.charset.StandardCharsets;
22 import java.util.Iterator;
23 import java.util.List;
26 import java.util.concurrent.ConcurrentHashMap;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.eclipse.jetty.client.HttpClient;
30 import org.eclipse.jetty.client.api.Request;
31 import org.eclipse.jetty.client.util.BytesContentProvider;
32 import org.eclipse.jetty.http.HttpField;
33 import org.eclipse.jetty.http.HttpFields;
34 import org.eclipse.jetty.http.HttpMethod;
35 import org.eclipse.jetty.http.HttpStatus;
36 import org.eclipse.jetty.util.BufferUtil;
37 import org.eclipse.jetty.util.URIUtil;
38 import org.json.JSONException;
39 import org.json.JSONObject;
40 import org.openhab.core.OpenHAB;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
44 import io.socket.backo.Backoff;
45 import io.socket.client.IO;
46 import io.socket.client.IO.Options;
47 import io.socket.client.Manager;
48 import io.socket.client.Socket;
49 import io.socket.emitter.Emitter;
50 import io.socket.engineio.client.Transport;
51 import io.socket.parser.Packet;
52 import io.socket.parser.Parser;
53 import io.socket.thread.EventThread;
54 import okhttp3.OkHttpClient.Builder;
55 import okhttp3.logging.HttpLoggingInterceptor;
56 import okhttp3.logging.HttpLoggingInterceptor.Level;
59 * This class provides communication between openHAB and the openHAB Cloud service.
60 * It also implements async http proxy for serving requests from user to
61 * openHAB through the openHAB Cloud. It uses Socket.IO connection to connect to
62 * the openHAB Cloud service and Jetty Http client to send local http requests to
65 * @author Victor Belov - Initial contribution
66 * @author Kai Kreuzer - migrated code to new Jetty client and ESH APIs
68 public class CloudClient {
70 * Logger for this class
72 private final Logger logger = LoggerFactory.getLogger(CloudClient.class);
75 * This variable holds base URL for the openHAB Cloud connections
77 private final String baseURL;
80 * This variable holds openHAB's UUID for authenticating and connecting to the openHAB Cloud
82 private final String uuid;
85 * This variable holds openHAB's secret for authenticating and connecting to the openHAB Cloud
87 private final String secret;
90 * This variable holds local openHAB's base URL for connecting to the local openHAB instance
92 private final String localBaseUrl;
95 * This variable holds instance of Jetty HTTP client to make requests to local openHAB
97 private final HttpClient jettyClient;
100 * This map holds HTTP requests to local openHAB which are currently running
102 private final Map<Integer, Request> runningRequests = new ConcurrentHashMap<>();
105 * This variable indicates if connection to the openHAB Cloud is currently in an established state
107 private boolean isConnected;
110 * This variable holds version of local openHAB
112 private String openHABVersion;
115 * This variable holds instance of Socket.IO client class which provides communication
116 * with the openHAB Cloud
118 private Socket socket;
121 * The protocol of the openHAB-cloud URL.
123 private String protocol = "https";
126 * This variable holds instance of CloudClientListener which provides callbacks to communicate
127 * certain events from the openHAB Cloud back to openHAB
129 private CloudClientListener listener;
130 private boolean remoteAccessEnabled;
131 private Set<String> exposedItems;
134 * Back-off strategy for reconnecting when manual reconnection is needed
136 private final Backoff reconnectBackoff = new Backoff();
139 * Constructor of CloudClient
141 * @param uuid openHAB's UUID to connect to the openHAB Cloud
142 * @param secret openHAB's Secret to connect to the openHAB Cloud
143 * @param remoteAccessEnabled Allow the openHAB Cloud to be used as a remote proxy
144 * @param exposedItems Items that are made available to apps connected to the openHAB Cloud
146 public CloudClient(HttpClient httpClient, String uuid, String secret, String baseURL, String localBaseUrl,
147 boolean remoteAccessEnabled, Set<String> exposedItems) {
149 this.secret = secret;
150 this.baseURL = baseURL;
151 this.localBaseUrl = localBaseUrl;
152 this.remoteAccessEnabled = remoteAccessEnabled;
153 this.exposedItems = exposedItems;
154 this.jettyClient = httpClient;
155 reconnectBackoff.setMin(1000);
156 reconnectBackoff.setMax(30_000);
157 reconnectBackoff.setJitter(0.5);
161 * Connect to the openHAB Cloud
164 public void connect() {
166 Options options = new Options();
167 if (logger.isTraceEnabled()) {
168 // When trace level logging is enabled, we activate further logging of HTTP calls
169 // of the Socket.IO library
170 Builder okHttpBuilder = new Builder();
171 HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
172 loggingInterceptor.setLevel(Level.BASIC);
173 okHttpBuilder.addInterceptor(loggingInterceptor);
174 okHttpBuilder.addNetworkInterceptor(loggingInterceptor);
175 options.callFactory = okHttpBuilder.build();
176 options.webSocketFactory = okHttpBuilder.build();
178 socket = IO.socket(baseURL, options);
179 URL parsed = new URL(baseURL);
180 protocol = parsed.getProtocol();
181 } catch (URISyntaxException e) {
182 logger.error("Error creating Socket.IO: {}", e.getMessage());
184 } catch (MalformedURLException e) {
185 logger.error("Error parsing baseURL to get protocol, assuming https. Error: {}", e.getMessage());
189 // socket manager events
192 .on(Manager.EVENT_TRANSPORT, args -> {
193 logger.trace("Manager.EVENT_TRANSPORT");
194 Transport transport = (Transport) args[0];
195 transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
197 public void call(Object... args) {
198 logger.trace("Transport.EVENT_REQUEST_HEADERS");
199 @SuppressWarnings("unchecked")
200 Map<String, List<String>> headers = (Map<String, List<String>>) args[0];
201 headers.put("uuid", List.of(uuid));
202 headers.put("secret", List.of(secret));
203 headers.put("openhabversion", List.of(OpenHAB.getVersion()));
204 headers.put("clientversion", List.of(CloudService.clientVersion));
205 headers.put("remoteaccess", List.of(((Boolean) remoteAccessEnabled).toString()));
209 .on(Manager.EVENT_CONNECT_ERROR, args -> {
210 if (args.length > 0) {
211 if (args[0] instanceof Exception) {
212 Exception e = (Exception) args[0];
214 "Error connecting to the openHAB Cloud instance: {} {}. Should reconnect automatically.",
215 e.getClass().getSimpleName(), e.getMessage());
218 "Error connecting to the openHAB Cloud instance: {}. Should reconnect automatically.",
222 logger.debug("Error connecting to the openHAB Cloud instance. Should reconnect automatically.");
225 .on(Manager.EVENT_OPEN, args -> logger.debug("Socket.IO OPEN"))//
226 .on(Manager.EVENT_CLOSE, args -> logger.debug("Socket.IO CLOSE: {}", args[0]))//
227 .on(Manager.EVENT_PACKET, args -> {
228 int packetTypeIndex = -1;
229 String type = "<unexpected packet type>";
230 if (args.length == 1 && args[0] instanceof Packet<?>) {
231 packetTypeIndex = ((Packet<?>) args[0]).type;
233 if (packetTypeIndex < Parser.types.length) {
234 type = Parser.types[packetTypeIndex];
236 type = "<unknown type>";
239 logger.trace("Socket.IO Packet: {} ({})", type, packetTypeIndex);
246 socket.on(Socket.EVENT_CONNECT, args -> {
247 logger.debug("Socket.IO connected");
251 .on(Socket.EVENT_CONNECTING, args -> logger.debug("Socket.IO connecting"))//
252 .on(Socket.EVENT_RECONNECTING, args -> logger.debug("Socket.IO re-connecting (attempt {})", args[0]))//
253 .on(Socket.EVENT_RECONNECT,
254 args -> logger.debug("Socket.IO re-connected successfully (attempt {})", args[0]))//
255 .on(Socket.EVENT_RECONNECT_ERROR, args -> {
256 if (args[0] instanceof Exception) {
257 Exception e = (Exception) args[0];
258 logger.debug("Socket.IO re-connect attempt error: {} {}", e.getClass().getSimpleName(),
261 logger.debug("Socket.IO re-connect attempt error: {}", args[0]);
264 .on(Socket.EVENT_RECONNECT_FAILED,
265 args -> logger.debug("Socket.IO re-connect attempts failed. Stopping reconnection."))//
266 .on(Socket.EVENT_DISCONNECT, args -> {
267 if (args.length > 0) {
268 logger.warn("Socket.IO disconnected: {}", args[0]);
270 logger.warn("Socket.IO disconnected");
275 .on(Socket.EVENT_ERROR, args -> {
276 if (CloudClient.this.socket.connected()) {
277 if (args.length > 0) {
278 if (args[0] instanceof Exception) {
279 Exception e = (Exception) args[0];
280 logger.warn("Error during communication: {} {}", e.getClass().getSimpleName(),
283 logger.warn("Error during communication: {}", args[0]);
286 logger.warn("Error during communication");
289 // We are not connected currently, manual reconnection is needed to keep trying to
293 // Socket.IO 1.x java client: 'error' event is emitted from Socket on connection errors that
295 // retried, but also with error that are automatically retried. If we
297 // Note how this is different in Socket.IO 2.x java client, Socket emits 'connect_error'
299 // OBS: Don't get confused with Socket IO 2.x docs online, in 1.x connect_error is emitted
301 // errors that are retried by the library automatically!
302 long delay = reconnectBackoff.duration();
303 // Try reconnecting on connection errors
304 if (args.length > 0) {
305 if (args[0] instanceof Exception) {
306 Exception e = (Exception) args[0];
308 "Error connecting to the openHAB Cloud instance: {} {}. Reconnecting after {} ms.",
309 e.getClass().getSimpleName(), e.getMessage(), delay);
312 "Error connecting to the openHAB Cloud instance: {}. Reconnecting after {} ms.",
316 logger.warn("Error connecting to the openHAB Cloud instance. Reconnecting.");
319 sleepSocketIO(delay);
324 .on(Socket.EVENT_PING, args -> logger.debug("Socket.IO ping"))//
325 .on(Socket.EVENT_PONG, args -> logger.debug("Socket.IO pong: {} ms", args[0]))//
326 .on("request", args -> onEvent("request", (JSONObject) args[0]))//
327 .on("cancel", args -> onEvent("cancel", (JSONObject) args[0]))//
328 .on("command", args -> onEvent("command", (JSONObject) args[0]))//
334 * Callback method for socket.io client which is called when connection is established
337 public void onConnect() {
338 logger.info("Connected to the openHAB Cloud service (UUID = {}, base URL = {})", censored(this.uuid),
340 reconnectBackoff.reset();
345 * Callback method for socket.io client which is called when disconnect occurs
348 public void onDisconnect() {
349 logger.info("Disconnected from the openHAB Cloud service (UUID = {}, base URL = {})", censored(this.uuid),
352 // And clean up the list of running requests
353 runningRequests.clear();
357 * Callback method for socket.io client which is called when a message is received
360 public void onEvent(String event, JSONObject data) {
361 logger.debug("on(): {}", event);
362 if ("command".equals(event)) {
363 handleCommandEvent(data);
366 if (remoteAccessEnabled) {
367 if ("request".equals(event)) {
368 handleRequestEvent(data);
369 } else if ("cancel".equals(event)) {
370 handleCancelEvent(data);
372 logger.warn("Unsupported event from openHAB Cloud: {}", event);
377 private void handleRequestEvent(JSONObject data) {
379 // Get unique request Id
380 int requestId = data.getInt("id");
381 logger.debug("Got request {}", requestId);
383 String requestPath = data.getString("path");
384 logger.debug("Path {}", requestPath);
385 // Get request method
386 String requestMethod = data.getString("method");
387 logger.debug("Method {}", requestMethod);
388 // Get JSONObject for request headers
389 JSONObject requestHeadersJson = data.getJSONObject("headers");
390 logger.debug("Headers: {}", requestHeadersJson.toString());
392 String requestBody = data.getString("body");
393 logger.trace("Body {}", requestBody);
394 // Get JSONObject for request query parameters
395 JSONObject requestQueryJson = data.getJSONObject("query");
396 logger.debug("Query {}", requestQueryJson.toString());
397 // Create URI builder with base request URI of openHAB and path from request
398 String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
399 Iterator<String> queryIterator = requestQueryJson.keys();
400 // Add query parameters to URI builder, if any
402 while (queryIterator.hasNext()) {
403 String queryName = queryIterator.next();
404 newPath += queryName;
406 newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
407 if (queryIterator.hasNext()) {
411 // Finally get the future request URI
412 URI requestUri = new URI(newPath);
413 // All preparations which are common for different methods are done
414 // Now perform the request to openHAB
416 logger.debug("Request method is {}", requestMethod);
417 Request request = jettyClient.newRequest(requestUri);
418 setRequestHeaders(request, requestHeadersJson);
419 String proto = protocol;
420 if (data.has("protocol")) {
421 proto = data.getString("protocol");
423 request.header("X-Forwarded-Proto", proto);
424 HttpMethod method = HttpMethod.fromString(requestMethod);
425 if (method == null) {
426 logger.debug("Unsupported request method {}", requestMethod);
429 request.method(method);
430 if (!requestBody.isEmpty()) {
431 request.content(new BytesContentProvider(requestBody.getBytes()));
434 request.onResponseHeaders(response -> {
435 logger.debug("onHeaders {}", requestId);
436 JSONObject responseJson = new JSONObject();
438 responseJson.put("id", requestId);
439 responseJson.put("headers", getJSONHeaders(response.getHeaders()));
440 responseJson.put("responseStatusCode", response.getStatus());
441 responseJson.put("responseStatusText", "OK");
442 socket.emit("responseHeader", responseJson);
443 logger.trace("Sent headers to request {}", requestId);
444 logger.trace("{}", responseJson.toString());
445 } catch (JSONException e) {
446 logger.debug("{}", e.getMessage());
448 }).onResponseContent((theResponse, content) -> {
449 logger.debug("onResponseContent: {}, content size {}", requestId, String.valueOf(content.remaining()));
450 JSONObject responseJson = new JSONObject();
452 responseJson.put("id", requestId);
453 responseJson.put("body", BufferUtil.toArray(content));
454 if (logger.isTraceEnabled()) {
455 logger.trace("{}", StandardCharsets.UTF_8.decode(content).toString());
457 socket.emit("responseContentBinary", responseJson);
458 logger.trace("Sent content to request {}", requestId);
459 } catch (JSONException e) {
460 logger.debug("{}", e.getMessage());
462 }).onRequestFailure((origRequest, failure) -> {
463 logger.debug("onRequestFailure: {}, {}", requestId, failure.getMessage());
464 JSONObject responseJson = new JSONObject();
466 responseJson.put("id", requestId);
467 responseJson.put("responseStatusText", "openHAB connection error: " + failure.getMessage());
468 socket.emit("responseError", responseJson);
469 } catch (JSONException e) {
470 logger.debug("{}", e.getMessage());
473 logger.debug("onComplete: {}", requestId);
474 // Remove this request from list of running requests
475 runningRequests.remove(requestId);
476 if ((result != null && result.isFailed())
477 && (result.getResponse() != null && result.getResponse().getStatus() != HttpStatus.OK_200)) {
478 if (result.getFailure() != null) {
479 logger.debug("Jetty request {} failed: {}", requestId, result.getFailure().getMessage());
481 if (result.getRequestFailure() != null) {
482 logger.debug("Request Failure: {}", result.getRequestFailure().getMessage());
484 if (result.getResponseFailure() != null) {
485 logger.debug("Response Failure: {}", result.getResponseFailure().getMessage());
488 JSONObject responseJson = new JSONObject();
490 responseJson.put("id", requestId);
491 socket.emit("responseFinished", responseJson);
492 logger.debug("Finished responding to request {}", requestId);
493 } catch (JSONException e) {
494 logger.debug("{}", e.getMessage());
498 // If successfully submitted request to http client, add it to the list of currently
499 // running requests to be able to cancel it if needed
500 runningRequests.put(requestId, request);
501 } catch (JSONException | IOException | URISyntaxException e) {
502 logger.debug("{}", e.getMessage());
506 private void setRequestHeaders(Request request, JSONObject requestHeadersJson) {
507 Iterator<String> headersIterator = requestHeadersJson.keys();
508 // Convert JSONObject of headers into Header ArrayList
509 while (headersIterator.hasNext()) {
510 String headerName = headersIterator.next();
513 headerValue = requestHeadersJson.getString(headerName);
514 logger.debug("Jetty set header {} = {}", headerName, headerValue);
515 if (!headerName.equalsIgnoreCase("Content-Length")) {
516 request.header(headerName, headerValue);
518 } catch (JSONException e) {
519 logger.warn("Error processing request headers: {}", e.getMessage());
524 private void handleCancelEvent(JSONObject data) {
526 int requestId = data.getInt("id");
527 logger.debug("Received cancel for request {}", requestId);
528 // Find and abort running request
529 Request request = runningRequests.get(requestId);
530 if (request != null) {
531 request.abort(new InterruptedException());
532 runningRequests.remove(requestId);
534 } catch (JSONException e) {
535 logger.debug("{}", e.getMessage());
539 private void handleCommandEvent(JSONObject data) {
540 String itemName = data.getString("item");
541 if (exposedItems.contains(itemName)) {
543 logger.debug("Received command {} for item {}.", data.getString("command"), itemName);
544 if (this.listener != null) {
545 this.listener.sendCommand(itemName, data.getString("command"));
547 } catch (JSONException e) {
548 logger.debug("{}", e.getMessage());
551 logger.warn("Received command from openHAB Cloud for item '{}', which is not exposed.", itemName);
556 * This method sends notification to the openHAB Cloud
558 * @param userId openHAB Cloud user id
559 * @param message notification message text
560 * @param icon name of the icon for this notification
561 * @param severity severity name for this notification
563 public void sendNotification(String userId, String message, @Nullable String icon, @Nullable String severity) {
565 JSONObject notificationMessage = new JSONObject();
567 notificationMessage.put("userId", userId);
568 notificationMessage.put("message", message);
569 notificationMessage.put("icon", icon);
570 notificationMessage.put("severity", severity);
571 socket.emit("notification", notificationMessage);
572 } catch (JSONException e) {
573 logger.debug("{}", e.getMessage());
576 logger.debug("No connection, notification is not sent");
581 * This method sends log notification to the openHAB Cloud
583 * @param message notification message text
584 * @param icon name of the icon for this notification
585 * @param severity severity name for this notification
587 public void sendLogNotification(String message, @Nullable String icon, @Nullable String severity) {
589 JSONObject notificationMessage = new JSONObject();
591 notificationMessage.put("message", message);
592 notificationMessage.put("icon", icon);
593 notificationMessage.put("severity", severity);
594 socket.emit("lognotification", notificationMessage);
595 } catch (JSONException e) {
596 logger.debug("{}", e.getMessage());
599 logger.debug("No connection, notification is not sent");
604 * This method sends broadcast notification to the openHAB Cloud
606 * @param message notification message text
607 * @param icon name of the icon for this notification
608 * @param severity severity name for this notification
610 public void sendBroadcastNotification(String message, @Nullable String icon, @Nullable String severity) {
612 JSONObject notificationMessage = new JSONObject();
614 notificationMessage.put("message", message);
615 notificationMessage.put("icon", icon);
616 notificationMessage.put("severity", severity);
617 socket.emit("broadcastnotification", notificationMessage);
618 } catch (JSONException e) {
619 logger.debug("{}", e.getMessage());
622 logger.debug("No connection, notification is not sent");
627 * Send item update to openHAB Cloud
629 * @param itemName the name of the item
630 * @param itemState updated item state
633 public void sendItemUpdate(String itemName, String itemState) {
635 logger.debug("Sending update '{}' for item '{}'", itemState, itemName);
636 JSONObject itemUpdateMessage = new JSONObject();
638 itemUpdateMessage.put("itemName", itemName);
639 itemUpdateMessage.put("itemStatus", itemState);
640 socket.emit("itemupdate", itemUpdateMessage);
641 } catch (JSONException e) {
642 logger.debug("{}", e.getMessage());
645 logger.debug("No connection, Item update is not sent");
650 * Returns true if openHAB Cloud connection is active
652 public boolean isConnected() {
657 * Disconnect from openHAB Cloud
659 public void shutdown() {
660 logger.info("Shutting down openHAB Cloud service connection");
664 public String getOpenHABVersion() {
665 return openHABVersion;
668 public void setOpenHABVersion(String openHABVersion) {
669 this.openHABVersion = openHABVersion;
672 public void setListener(CloudClientListener listener) {
673 this.listener = listener;
676 private JSONObject getJSONHeaders(HttpFields httpFields) {
677 JSONObject headersJSON = new JSONObject();
679 for (HttpField field : httpFields) {
680 headersJSON.put(field.getName(), field.getValue());
682 } catch (JSONException e) {
683 logger.warn("Error forming response headers: {}", e.getMessage());
688 private void sleepSocketIO(long delay) {
689 EventThread.exec(() -> {
692 } catch (InterruptedException e) {
698 private static String censored(String secret) {
699 if (secret.length() < 4) {
702 return secret.substring(0, 2) + "..." + secret.substring(secret.length() - 2, secret.length());