2 * Copyright (c) 2010-2021 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.client.IO;
45 import io.socket.client.Manager;
46 import io.socket.client.Socket;
47 import io.socket.emitter.Emitter;
48 import io.socket.engineio.client.Transport;
51 * This class provides communication between openHAB and the openHAB Cloud service.
52 * It also implements async http proxy for serving requests from user to
53 * openHAB through the openHAB Cloud. It uses Socket.IO connection to connect to
54 * the openHAB Cloud service and Jetty Http client to send local http requests to
57 * @author Victor Belov - Initial contribution
58 * @author Kai Kreuzer - migrated code to new Jetty client and ESH APIs
60 public class CloudClient {
62 * Logger for this class
64 private final Logger logger = LoggerFactory.getLogger(CloudClient.class);
67 * This variable holds base URL for the openHAB Cloud connections
69 private final String baseURL;
72 * This variable holds openHAB's UUID for authenticating and connecting to the openHAB Cloud
74 private final String uuid;
77 * This variable holds openHAB's secret for authenticating and connecting to the openHAB Cloud
79 private final String secret;
82 * This variable holds local openHAB's base URL for connecting to the local openHAB instance
84 private final String localBaseUrl;
87 * This variable holds instance of Jetty HTTP client to make requests to local openHAB
89 private final HttpClient jettyClient;
92 * This map holds HTTP requests to local openHAB which are currently running
94 private final Map<Integer, Request> runningRequests = new ConcurrentHashMap<>();
97 * This variable indicates if connection to the openHAB Cloud is currently in an established state
99 private boolean isConnected;
102 * This variable holds version of local openHAB
104 private String openHABVersion;
107 * This variable holds instance of Socket.IO client class which provides communication
108 * with the openHAB Cloud
110 private Socket socket;
113 * The protocol of the openHAB-cloud URL.
115 private String protocol = "https";
118 * This variable holds instance of CloudClientListener which provides callbacks to communicate
119 * certain events from the openHAB Cloud back to openHAB
121 private CloudClientListener listener;
122 private boolean remoteAccessEnabled;
123 private Set<String> exposedItems;
126 * Constructor of CloudClient
128 * @param uuid openHAB's UUID to connect to the openHAB Cloud
129 * @param secret openHAB's Secret to connect to the openHAB Cloud
130 * @param remoteAccessEnabled Allow the openHAB Cloud to be used as a remote proxy
131 * @param exposedItems Items that are made available to apps connected to the openHAB Cloud
133 public CloudClient(HttpClient httpClient, String uuid, String secret, String baseURL, String localBaseUrl,
134 boolean remoteAccessEnabled, Set<String> exposedItems) {
136 this.secret = secret;
137 this.baseURL = baseURL;
138 this.localBaseUrl = localBaseUrl;
139 this.remoteAccessEnabled = remoteAccessEnabled;
140 this.exposedItems = exposedItems;
141 this.jettyClient = httpClient;
145 * Connect to the openHAB Cloud
148 public void connect() {
150 socket = IO.socket(baseURL);
151 URL parsed = new URL(baseURL);
152 protocol = parsed.getProtocol();
153 } catch (URISyntaxException e) {
154 logger.error("Error creating Socket.IO: {}", e.getMessage());
155 } catch (MalformedURLException e) {
156 logger.error("Error parsing baseURL to get protocol, assuming https. Error: {}", e.getMessage());
158 socket.io().on(Manager.EVENT_TRANSPORT, new Emitter.Listener() {
160 public void call(Object... args) {
161 logger.trace("Manager.EVENT_TRANSPORT");
162 Transport transport = (Transport) args[0];
163 transport.on(Transport.EVENT_REQUEST_HEADERS, new Emitter.Listener() {
165 public void call(Object... args) {
166 logger.trace("Transport.EVENT_REQUEST_HEADERS");
167 @SuppressWarnings("unchecked")
168 Map<String, List<String>> headers = (Map<String, List<String>>) args[0];
169 headers.put("uuid", List.of(uuid));
170 headers.put("secret", List.of(secret));
171 headers.put("openhabversion", List.of(OpenHAB.getVersion()));
172 headers.put("clientversion", List.of(CloudService.clientVersion));
173 headers.put("remoteaccess", List.of(((Boolean) remoteAccessEnabled).toString()));
178 socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
180 public void call(Object... args) {
181 logger.debug("Socket.IO connected");
185 }).on(Socket.EVENT_DISCONNECT, new Emitter.Listener() {
187 public void call(Object... args) {
188 logger.debug("Socket.IO disconnected");
192 }).on(Socket.EVENT_ERROR, new Emitter.Listener() {
194 public void call(Object... args) {
195 if (logger.isDebugEnabled()) {
196 logger.error("Error connecting to the openHAB Cloud instance: {}", args[0]);
198 logger.error("Error connecting to the openHAB Cloud instance");
201 }).on("request", new Emitter.Listener() {
203 public void call(Object... args) {
204 onEvent("request", (JSONObject) args[0]);
206 }).on("cancel", new Emitter.Listener() {
208 public void call(Object... args) {
209 onEvent("cancel", (JSONObject) args[0]);
211 }).on("command", new Emitter.Listener() {
214 public void call(Object... args) {
215 onEvent("command", (JSONObject) args[0]);
222 * Callback method for socket.io client which is called when connection is established
225 public void onConnect() {
226 logger.info("Connected to the openHAB Cloud service (UUID = {}, base URL = {})", this.uuid, this.localBaseUrl);
231 * Callback method for socket.io client which is called when disconnect occurs
234 public void onDisconnect() {
235 logger.info("Disconnected from the openHAB Cloud service (UUID = {}, base URL = {})", this.uuid,
238 // And clean up the list of running requests
239 runningRequests.clear();
243 * Callback method for socket.io client which is called when an error occurs
246 public void onError(IOException error) {
247 logger.debug("{}", error.getMessage());
251 * Callback method for socket.io client which is called when a message is received
254 public void onEvent(String event, JSONObject data) {
255 logger.debug("on(): {}", event);
256 if ("command".equals(event)) {
257 handleCommandEvent(data);
260 if (remoteAccessEnabled) {
261 if ("request".equals(event)) {
262 handleRequestEvent(data);
263 } else if ("cancel".equals(event)) {
264 handleCancelEvent(data);
266 logger.warn("Unsupported event from openHAB Cloud: {}", event);
271 private void handleRequestEvent(JSONObject data) {
273 // Get unique request Id
274 int requestId = data.getInt("id");
275 logger.debug("Got request {}", requestId);
277 String requestPath = data.getString("path");
278 logger.debug("Path {}", requestPath);
279 // Get request method
280 String requestMethod = data.getString("method");
281 logger.debug("Method {}", requestMethod);
282 // Get JSONObject for request headers
283 JSONObject requestHeadersJson = data.getJSONObject("headers");
284 logger.debug("Headers: {}", requestHeadersJson.toString());
286 String requestBody = data.getString("body");
287 logger.trace("Body {}", requestBody);
288 // Get JSONObject for request query parameters
289 JSONObject requestQueryJson = data.getJSONObject("query");
290 logger.debug("Query {}", requestQueryJson.toString());
291 // Create URI builder with base request URI of openHAB and path from request
292 String newPath = URIUtil.addPaths(localBaseUrl, requestPath);
293 Iterator<String> queryIterator = requestQueryJson.keys();
294 // Add query parameters to URI builder, if any
296 while (queryIterator.hasNext()) {
297 String queryName = queryIterator.next();
298 newPath += queryName;
300 newPath += URLEncoder.encode(requestQueryJson.getString(queryName), "UTF-8");
301 if (queryIterator.hasNext()) {
305 // Finally get the future request URI
306 URI requestUri = new URI(newPath);
307 // All preparations which are common for different methods are done
308 // Now perform the request to openHAB
310 logger.debug("Request method is {}", requestMethod);
311 Request request = jettyClient.newRequest(requestUri);
312 setRequestHeaders(request, requestHeadersJson);
313 String proto = protocol;
314 if (data.has("protocol")) {
315 proto = data.getString("protocol");
317 request.header("X-Forwarded-Proto", proto);
318 HttpMethod method = HttpMethod.fromString(requestMethod);
319 if (method == null) {
320 logger.debug("Unsupported request method {}", requestMethod);
323 request.method(method);
324 if (!requestBody.isEmpty()) {
325 request.content(new BytesContentProvider(requestBody.getBytes()));
328 request.onResponseHeaders(response -> {
329 logger.debug("onHeaders {}", requestId);
330 JSONObject responseJson = new JSONObject();
332 responseJson.put("id", requestId);
333 responseJson.put("headers", getJSONHeaders(response.getHeaders()));
334 responseJson.put("responseStatusCode", response.getStatus());
335 responseJson.put("responseStatusText", "OK");
336 socket.emit("responseHeader", responseJson);
337 logger.trace("Sent headers to request {}", requestId);
338 logger.trace("{}", responseJson.toString());
339 } catch (JSONException e) {
340 logger.debug("{}", e.getMessage());
342 }).onResponseContent((theResponse, content) -> {
343 logger.debug("onResponseContent: {}, content size {}", requestId, String.valueOf(content.remaining()));
344 JSONObject responseJson = new JSONObject();
346 responseJson.put("id", requestId);
347 responseJson.put("body", BufferUtil.toArray(content));
348 if (logger.isTraceEnabled()) {
349 logger.trace("{}", StandardCharsets.UTF_8.decode(content).toString());
351 socket.emit("responseContentBinary", responseJson);
352 logger.trace("Sent content to request {}", requestId);
353 } catch (JSONException e) {
354 logger.debug("{}", e.getMessage());
356 }).onRequestFailure((origRequest, failure) -> {
357 logger.debug("onRequestFailure: {}, {}", requestId, failure.getMessage());
358 JSONObject responseJson = new JSONObject();
360 responseJson.put("id", requestId);
361 responseJson.put("responseStatusText", "openHAB connection error: " + failure.getMessage());
362 socket.emit("responseError", responseJson);
363 } catch (JSONException e) {
364 logger.debug("{}", e.getMessage());
367 logger.debug("onComplete: {}", requestId);
368 // Remove this request from list of running requests
369 runningRequests.remove(requestId);
370 if ((result != null && result.isFailed())
371 && (result.getResponse() != null && result.getResponse().getStatus() != HttpStatus.OK_200)) {
372 if (result.getFailure() != null) {
373 logger.debug("Jetty request {} failed: {}", requestId, result.getFailure().getMessage());
375 if (result.getRequestFailure() != null) {
376 logger.debug("Request Failure: {}", result.getRequestFailure().getMessage());
378 if (result.getResponseFailure() != null) {
379 logger.debug("Response Failure: {}", result.getResponseFailure().getMessage());
382 JSONObject responseJson = new JSONObject();
384 responseJson.put("id", requestId);
385 socket.emit("responseFinished", responseJson);
386 logger.debug("Finished responding to request {}", requestId);
387 } catch (JSONException e) {
388 logger.debug("{}", e.getMessage());
392 // If successfully submitted request to http client, add it to the list of currently
393 // running requests to be able to cancel it if needed
394 runningRequests.put(requestId, request);
395 } catch (JSONException | IOException | URISyntaxException e) {
396 logger.debug("{}", e.getMessage());
400 private void setRequestHeaders(Request request, JSONObject requestHeadersJson) {
401 Iterator<String> headersIterator = requestHeadersJson.keys();
402 // Convert JSONObject of headers into Header ArrayList
403 while (headersIterator.hasNext()) {
404 String headerName = headersIterator.next();
407 headerValue = requestHeadersJson.getString(headerName);
408 logger.debug("Jetty set header {} = {}", headerName, headerValue);
409 if (!headerName.equalsIgnoreCase("Content-Length")) {
410 request.header(headerName, headerValue);
412 } catch (JSONException e) {
413 logger.warn("Error processing request headers: {}", e.getMessage());
418 private void handleCancelEvent(JSONObject data) {
420 int requestId = data.getInt("id");
421 logger.debug("Received cancel for request {}", requestId);
422 // Find and abort running request
423 Request request = runningRequests.get(requestId);
424 if (request != null) {
425 request.abort(new InterruptedException());
426 runningRequests.remove(requestId);
428 } catch (JSONException e) {
429 logger.debug("{}", e.getMessage());
433 private void handleCommandEvent(JSONObject data) {
434 String itemName = data.getString("item");
435 if (exposedItems.contains(itemName)) {
437 logger.debug("Received command {} for item {}.", data.getString("command"), itemName);
438 if (this.listener != null) {
439 this.listener.sendCommand(itemName, data.getString("command"));
441 } catch (JSONException e) {
442 logger.debug("{}", e.getMessage());
445 logger.warn("Received command from openHAB Cloud for item '{}', which is not exposed.", itemName);
450 * This method sends notification to the openHAB Cloud
452 * @param userId openHAB Cloud user id
453 * @param message notification message text
454 * @param icon name of the icon for this notification
455 * @param severity severity name for this notification
457 public void sendNotification(String userId, String message, @Nullable String icon, @Nullable String severity) {
459 JSONObject notificationMessage = new JSONObject();
461 notificationMessage.put("userId", userId);
462 notificationMessage.put("message", message);
463 notificationMessage.put("icon", icon);
464 notificationMessage.put("severity", severity);
465 socket.emit("notification", notificationMessage);
466 } catch (JSONException e) {
467 logger.debug("{}", e.getMessage());
470 logger.debug("No connection, notification is not sent");
475 * This method sends log notification to the openHAB Cloud
477 * @param message notification message text
478 * @param icon name of the icon for this notification
479 * @param severity severity name for this notification
481 public void sendLogNotification(String message, @Nullable String icon, @Nullable String severity) {
483 JSONObject notificationMessage = new JSONObject();
485 notificationMessage.put("message", message);
486 notificationMessage.put("icon", icon);
487 notificationMessage.put("severity", severity);
488 socket.emit("lognotification", notificationMessage);
489 } catch (JSONException e) {
490 logger.debug("{}", e.getMessage());
493 logger.debug("No connection, notification is not sent");
498 * This method sends broadcast notification to the openHAB Cloud
500 * @param message notification message text
501 * @param icon name of the icon for this notification
502 * @param severity severity name for this notification
504 public void sendBroadcastNotification(String message, @Nullable String icon, @Nullable String severity) {
506 JSONObject notificationMessage = new JSONObject();
508 notificationMessage.put("message", message);
509 notificationMessage.put("icon", icon);
510 notificationMessage.put("severity", severity);
511 socket.emit("broadcastnotification", notificationMessage);
512 } catch (JSONException e) {
513 logger.debug("{}", e.getMessage());
516 logger.debug("No connection, notification is not sent");
521 * Send item update to openHAB Cloud
523 * @param itemName the name of the item
524 * @param itemState updated item state
527 public void sendItemUpdate(String itemName, String itemState) {
529 logger.debug("Sending update '{}' for item '{}'", itemState, itemName);
530 JSONObject itemUpdateMessage = new JSONObject();
532 itemUpdateMessage.put("itemName", itemName);
533 itemUpdateMessage.put("itemStatus", itemState);
534 socket.emit("itemupdate", itemUpdateMessage);
535 } catch (JSONException e) {
536 logger.debug("{}", e.getMessage());
539 logger.debug("No connection, Item update is not sent");
544 * Returns true if openHAB Cloud connection is active
546 public boolean isConnected() {
551 * Disconnect from openHAB Cloud
553 public void shutdown() {
554 logger.info("Shutting down openHAB Cloud service connection");
558 public String getOpenHABVersion() {
559 return openHABVersion;
562 public void setOpenHABVersion(String openHABVersion) {
563 this.openHABVersion = openHABVersion;
566 public void setListener(CloudClientListener listener) {
567 this.listener = listener;
570 private JSONObject getJSONHeaders(HttpFields httpFields) {
571 JSONObject headersJSON = new JSONObject();
573 for (HttpField field : httpFields) {
574 headersJSON.put(field.getName(), field.getValue());
576 } catch (JSONException e) {
577 logger.warn("Error forming response headers: {}", e.getMessage());