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.hue.internal.connection;
15 import java.io.BufferedReader;
16 import java.io.ByteArrayInputStream;
17 import java.io.Closeable;
18 import java.io.IOException;
19 import java.io.InputStreamReader;
20 import java.io.Reader;
21 import java.net.InetSocketAddress;
22 import java.nio.ByteBuffer;
23 import java.nio.charset.StandardCharsets;
24 import java.time.Duration;
25 import java.time.Instant;
26 import java.util.ArrayList;
27 import java.util.Arrays;
28 import java.util.List;
30 import java.util.Objects;
31 import java.util.Optional;
32 import java.util.Properties;
33 import java.util.concurrent.CompletableFuture;
34 import java.util.concurrent.ConcurrentHashMap;
35 import java.util.concurrent.ExecutionException;
36 import java.util.concurrent.Future;
37 import java.util.concurrent.Semaphore;
38 import java.util.concurrent.TimeUnit;
39 import java.util.concurrent.TimeoutException;
40 import java.util.stream.Collectors;
42 import javax.ws.rs.core.MediaType;
44 import org.eclipse.jdt.annotation.NonNullByDefault;
45 import org.eclipse.jdt.annotation.Nullable;
46 import org.eclipse.jetty.client.HttpClient;
47 import org.eclipse.jetty.client.api.ContentResponse;
48 import org.eclipse.jetty.client.api.Request;
49 import org.eclipse.jetty.client.util.StringContentProvider;
50 import org.eclipse.jetty.http.HttpFields;
51 import org.eclipse.jetty.http.HttpHeader;
52 import org.eclipse.jetty.http.HttpMethod;
53 import org.eclipse.jetty.http.HttpStatus;
54 import org.eclipse.jetty.http.HttpURI;
55 import org.eclipse.jetty.http.HttpVersion;
56 import org.eclipse.jetty.http.MetaData;
57 import org.eclipse.jetty.http.MetaData.Response;
58 import org.eclipse.jetty.http2.api.Session;
59 import org.eclipse.jetty.http2.api.Stream;
60 import org.eclipse.jetty.http2.client.HTTP2Client;
61 import org.eclipse.jetty.http2.frames.DataFrame;
62 import org.eclipse.jetty.http2.frames.GoAwayFrame;
63 import org.eclipse.jetty.http2.frames.HeadersFrame;
64 import org.eclipse.jetty.http2.frames.PingFrame;
65 import org.eclipse.jetty.http2.frames.ResetFrame;
66 import org.eclipse.jetty.util.Callback;
67 import org.eclipse.jetty.util.Promise.Completable;
68 import org.eclipse.jetty.util.ssl.SslContextFactory;
69 import org.openhab.binding.hue.internal.dto.CreateUserRequest;
70 import org.openhab.binding.hue.internal.dto.SuccessResponse;
71 import org.openhab.binding.hue.internal.dto.clip2.BridgeConfig;
72 import org.openhab.binding.hue.internal.dto.clip2.Event;
73 import org.openhab.binding.hue.internal.dto.clip2.Resource;
74 import org.openhab.binding.hue.internal.dto.clip2.ResourceReference;
75 import org.openhab.binding.hue.internal.dto.clip2.Resources;
76 import org.openhab.binding.hue.internal.dto.clip2.enums.ResourceType;
77 import org.openhab.binding.hue.internal.exceptions.ApiException;
78 import org.openhab.binding.hue.internal.exceptions.HttpUnauthorizedException;
79 import org.openhab.binding.hue.internal.handler.Clip2BridgeHandler;
80 import org.openhab.core.io.net.http.HttpClientFactory;
81 import org.openhab.core.io.net.http.HttpUtil;
82 import org.slf4j.Logger;
83 import org.slf4j.LoggerFactory;
85 import com.google.gson.Gson;
86 import com.google.gson.JsonArray;
87 import com.google.gson.JsonElement;
88 import com.google.gson.JsonParseException;
89 import com.google.gson.JsonParser;
90 import com.google.gson.JsonSyntaxException;
93 * This class handles HTTP and SSE connections to/from a Hue Bridge running CLIP 2.
95 * It uses the following connection mechanisms:
97 * <li>The primary communication uses HTTP 2 streams over a shared permanent HTTP 2 session.</li>
98 * <li>The 'registerApplicationKey()' method uses HTTP/1.1 over the OH common Jetty client.</li>
99 * <li>The 'isClip2Supported()' static method uses HTTP/1.1 over the OH common Jetty client via 'HttpUtil'.</li>
101 * @author Andrew Fiddian-Green - Initial Contribution
104 public class Clip2Bridge implements Closeable {
107 * Base (abstract) adapter for listening to HTTP 2 stream events.
109 * It implements a CompletableFuture by means of which the caller can wait for the response data to come in. And
110 * which, in the case of fatal errors, gets completed exceptionally.
112 * It handles the following fatal error events by notifying the containing class:
114 * <li>onHeaders() HTTP unauthorized codes</li>
116 private abstract class BaseStreamListenerAdapter<T> extends Stream.Listener.Adapter {
117 protected final CompletableFuture<T> completable = new CompletableFuture<T>();
118 private String contentType = "UNDEFINED";
120 protected T awaitResult() throws ExecutionException, InterruptedException, TimeoutException {
121 return completable.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
125 * Return the HTTP content type.
127 * @return content type e.g. 'application/json'
129 protected String getContentType() {
133 protected void handleHttp2Error(Http2Error error) {
134 Http2Exception e = new Http2Exception(error);
135 if (Http2Error.UNAUTHORIZED.equals(error)) {
136 // for external error handling, abstract authorization errors into a separate exception
137 completable.completeExceptionally(new HttpUnauthorizedException("HTTP 2 request not authorized"));
139 completable.completeExceptionally(e);
141 fatalErrorDelayed(this, e);
145 * Check the reply headers to see whether the request was authorised.
148 public void onHeaders(@Nullable Stream stream, @Nullable HeadersFrame frame) {
149 Objects.requireNonNull(frame);
150 MetaData metaData = frame.getMetaData();
151 if (metaData.isResponse()) {
152 Response responseMetaData = (Response) metaData;
153 int httpStatus = responseMetaData.getStatus();
154 switch (httpStatus) {
155 case HttpStatus.UNAUTHORIZED_401:
156 case HttpStatus.FORBIDDEN_403:
157 handleHttp2Error(Http2Error.UNAUTHORIZED);
160 contentType = responseMetaData.getFields().get(HttpHeader.CONTENT_TYPE).toLowerCase();
166 * Adapter for listening to regular HTTP 2 GET/PUT request stream events.
168 * It assembles the incoming text data into an HTTP 'content' entity. And when the last data frame arrives, it
169 * returns the full content by completing the CompletableFuture with that data.
171 * In addition to those handled by the parent, it handles the following fatal error events by notifying the
174 * <li>onIdleTimeout()</li>
175 * <li>onTimeout()</li>
177 private class ContentStreamListenerAdapter extends BaseStreamListenerAdapter<String> {
178 private final DataFrameCollector content = new DataFrameCollector();
181 public void onData(@Nullable Stream stream, @Nullable DataFrame frame, @Nullable Callback callback) {
182 Objects.requireNonNull(frame);
183 Objects.requireNonNull(callback);
184 synchronized (this) {
185 content.append(frame.getData());
186 if (frame.isEndStream() && !completable.isDone()) {
187 completable.complete(content.contentAsString().trim());
191 callback.succeeded();
195 public boolean onIdleTimeout(@Nullable Stream stream, @Nullable Throwable x) {
196 handleHttp2Error(Http2Error.IDLE);
201 public void onTimeout(@Nullable Stream stream, @Nullable Throwable x) {
202 handleHttp2Error(Http2Error.TIMEOUT);
207 * Class to collect incoming ByteBuffer data from HTTP 2 Data frames.
209 private static class DataFrameCollector {
210 private byte[] buffer = new byte[512];
211 private int usedSize = 0;
213 public void append(ByteBuffer data) {
214 int dataCapacity = data.capacity();
215 int neededSize = usedSize + dataCapacity;
216 if (neededSize > buffer.length) {
217 int newSize = (dataCapacity < 4096) ? neededSize : Math.max(2 * buffer.length, neededSize);
218 buffer = Arrays.copyOf(buffer, newSize);
220 data.get(buffer, usedSize, dataCapacity);
221 usedSize += dataCapacity;
224 public String contentAsString() {
225 return new String(buffer, 0, usedSize, StandardCharsets.UTF_8);
228 public Reader contentStreamReader() {
229 return new InputStreamReader(new ByteArrayInputStream(buffer, 0, usedSize), StandardCharsets.UTF_8);
232 public void reset() {
238 * Adapter for listening to SSE event stream events.
240 * It receives the incoming text lines. Receipt of the first data line causes the CompletableFuture to complete. It
241 * then parses subsequent data according to the SSE specification. If the line starts with a 'data:' message, it
242 * adds the data to the list of strings. And if the line is empty (i.e. the last line of an event), it passes the
243 * full set of strings to the owner via a call-back method.
245 * The stream must be permanently connected, so it ignores onIdleTimeout() events.
247 * The parent class handles most fatal errors, but since the event stream is supposed to be permanently connected,
248 * the following events are also considered as fatal:
250 * <li>onClosed()</li>
253 private class EventStreamListenerAdapter extends BaseStreamListenerAdapter<Boolean> {
254 private final DataFrameCollector eventData = new DataFrameCollector();
257 public void onClosed(@Nullable Stream stream) {
258 handleHttp2Error(Http2Error.CLOSED);
262 public void onData(@Nullable Stream stream, @Nullable DataFrame frame, @Nullable Callback callback) {
263 Objects.requireNonNull(frame);
264 Objects.requireNonNull(callback);
265 synchronized (this) {
266 eventData.append(frame.getData());
267 BufferedReader reader = new BufferedReader(eventData.contentStreamReader());
268 @SuppressWarnings("null")
269 List<String> receivedLines = reader.lines().collect(Collectors.toList());
271 // a blank line marks the end of an SSE message
272 boolean endOfMessage = !receivedLines.isEmpty()
273 && receivedLines.get(receivedLines.size() - 1).isBlank();
277 // receipt of ANY message means the event stream is established
278 if (!completable.isDone()) {
279 completable.complete(Boolean.TRUE);
281 // append any 'data' field values to the event message
282 StringBuilder eventContent = new StringBuilder();
283 for (String receivedLine : receivedLines) {
284 if (receivedLine.startsWith("data:")) {
285 eventContent.append(receivedLine.substring(5).stripLeading());
288 if (eventContent.length() > 0) {
289 onEventData(eventContent.toString().trim());
293 callback.succeeded();
297 public boolean onIdleTimeout(@Nullable Stream stream, @Nullable Throwable x) {
302 public void onReset(@Nullable Stream stream, @Nullable ResetFrame frame) {
303 handleHttp2Error(Http2Error.RESET);
308 * Enum of potential fatal HTTP 2 session/stream errors.
310 private enum Http2Error {
321 * Private exception for handling HTTP 2 stream and session errors.
323 @SuppressWarnings("serial")
324 private static class Http2Exception extends ApiException {
325 public final Http2Error error;
327 public Http2Exception(Http2Error error) {
331 public Http2Exception(Http2Error error, @Nullable Throwable cause) {
332 super("HTTP 2 stream " + error.toString().toLowerCase(), cause);
338 * Adapter for listening to HTTP 2 session status events.
340 * The session must be permanently connected, so it ignores onIdleTimeout() events.
341 * It also handles the following fatal events by notifying the containing class:
344 * <li>onFailure()</li>
345 * <li>onGoAway()</li>
348 private class SessionListenerAdapter extends Session.Listener.Adapter {
351 public void onClose(@Nullable Session session, @Nullable GoAwayFrame frame) {
352 fatalErrorDelayed(this, new Http2Exception(Http2Error.CLOSED));
356 public void onFailure(@Nullable Session session, @Nullable Throwable failure) {
357 fatalErrorDelayed(this, new Http2Exception(Http2Error.FAILURE));
361 public void onGoAway(@Nullable Session session, @Nullable GoAwayFrame frame) {
362 fatalErrorDelayed(this, new Http2Exception(Http2Error.GO_AWAY));
366 public boolean onIdleTimeout(@Nullable Session session) {
371 public void onPing(@Nullable Session session, @Nullable PingFrame frame) {
373 if (Objects.nonNull(session) && Objects.nonNull(frame) && !frame.isReply()) {
374 session.ping(new PingFrame(true), Callback.NOOP);
379 public void onReset(@Nullable Session session, @Nullable ResetFrame frame) {
380 fatalErrorDelayed(this, new Http2Exception(Http2Error.RESET));
385 * Enum showing the online state of the session connection.
387 private static enum State {
393 * Session open for HTTP calls only
397 * Session open for HTTP calls and actively receiving SSE events
402 private static final Logger LOGGER = LoggerFactory.getLogger(Clip2Bridge.class);
404 private static final String APPLICATION_ID = "org-openhab-binding-hue-clip2";
405 private static final String APPLICATION_KEY = "hue-application-key";
407 private static final String EVENT_STREAM_ID = "eventStream";
408 private static final String FORMAT_URL_CONFIG = "http://%s/api/0/config";
409 private static final String FORMAT_URL_RESOURCE = "https://%s/clip/v2/resource/";
410 private static final String FORMAT_URL_REGISTER = "http://%s/api";
411 private static final String FORMAT_URL_EVENTS = "https://%s/eventstream/clip/v2";
413 private static final long CLIP2_MINIMUM_VERSION = 1948086000L;
415 public static final int TIMEOUT_SECONDS = 10;
416 private static final int CHECK_ALIVE_SECONDS = 300;
417 private static final int REQUEST_INTERVAL_MILLISECS = 50;
418 private static final int MAX_CONCURRENT_STREAMS = 3;
420 private static final ResourceReference BRIDGE = new ResourceReference().setType(ResourceType.BRIDGE);
423 * Static method to attempt to connect to a Hue Bridge, get its software version, and check if it is high enough to
424 * support the CLIP 2 API.
426 * @param hostName the bridge IP address.
427 * @return true if bridge is online and it supports CLIP 2, or false if it is online and does not support CLIP 2.
428 * @throws IOException if unable to communicate with the bridge.
429 * @throws NumberFormatException if the bridge firmware version is invalid.
431 public static boolean isClip2Supported(String hostName) throws IOException {
433 Properties headers = new Properties();
434 headers.put(HttpHeader.ACCEPT, MediaType.APPLICATION_JSON);
435 response = HttpUtil.executeUrl("GET", String.format(FORMAT_URL_CONFIG, hostName), headers, null, null,
436 TIMEOUT_SECONDS * 1000);
437 BridgeConfig config = new Gson().fromJson(response, BridgeConfig.class);
438 if (Objects.nonNull(config)) {
439 String swVersion = config.swversion;
440 if (Objects.nonNull(swVersion)) {
442 if (Long.parseLong(swVersion) >= CLIP2_MINIMUM_VERSION) {
445 } catch (NumberFormatException e) {
446 LOGGER.debug("isClip2Supported() swVersion '{}' is not a number", swVersion);
453 private final HttpClient httpClient;
454 private final HTTP2Client http2Client;
455 private final String hostName;
456 private final String baseUrl;
457 private final String eventUrl;
458 private final String registrationUrl;
459 private final String applicationKey;
460 private final Clip2BridgeHandler bridgeHandler;
461 private final Gson jsonParser = new Gson();
462 private final Semaphore streamMutex = new Semaphore(MAX_CONCURRENT_STREAMS, true);
464 private boolean closing;
465 private State onlineState = State.CLOSED;
466 private Optional<Instant> lastRequestTime = Optional.empty();
467 private Instant sessionExpireTime = Instant.MAX;
468 private @Nullable Session http2Session;
470 private @Nullable Future<?> checkAliveTask;
471 private Map<Integer, Future<?>> fatalErrorTasks = new ConcurrentHashMap<>();
476 * @param httpClientFactory the OH core HttpClientFactory.
477 * @param bridgeHandler the bridge handler.
478 * @param hostName the host name (ip address) of the Hue bridge
479 * @param applicationKey the application key.
480 * @throws ApiException if unable to open Jetty HTTP/2 client.
482 public Clip2Bridge(HttpClientFactory httpClientFactory, Clip2BridgeHandler bridgeHandler, String hostName,
483 String applicationKey) throws ApiException {
484 LOGGER.debug("Clip2Bridge()");
485 httpClient = httpClientFactory.getCommonHttpClient();
486 http2Client = httpClientFactory.createHttp2Client("hue-clip2", httpClient.getSslContextFactory());
487 http2Client.setConnectTimeout(Clip2Bridge.TIMEOUT_SECONDS * 1000);
488 http2Client.setIdleTimeout(-1);
491 } catch (Exception e) {
492 throw new ApiException("Error starting HTTP/2 client", e);
494 this.bridgeHandler = bridgeHandler;
495 this.hostName = hostName;
496 this.applicationKey = applicationKey;
497 baseUrl = String.format(FORMAT_URL_RESOURCE, hostName);
498 eventUrl = String.format(FORMAT_URL_EVENTS, hostName);
499 registrationUrl = String.format(FORMAT_URL_REGISTER, hostName);
503 * Cancel the given task.
505 * @param cancelTask the task to be cancelled (may be null)
506 * @param mayInterrupt allows cancel() to interrupt the thread.
508 private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
509 if (Objects.nonNull(cancelTask)) {
510 cancelTask.cancel(mayInterrupt);
515 * Send a ping to the Hue bridge to check that the session is still alive.
517 private void checkAlive() {
518 if (onlineState == State.CLOSED) {
521 LOGGER.debug("checkAlive()");
522 Session session = http2Session;
523 if (Objects.nonNull(session)) {
524 session.ping(new PingFrame(false), Callback.NOOP);
526 if (Instant.now().isAfter(sessionExpireTime)) {
527 fatalError(this, new Http2Exception(Http2Error.TIMEOUT));
532 * Connection is ok, so reschedule the session check alive expire time. Called in response to incoming ping frames
535 protected void checkAliveOk() {
536 LOGGER.debug("checkAliveOk()");
537 sessionExpireTime = Instant.now().plusSeconds(CHECK_ALIVE_SECONDS * 2);
541 * Close the connection.
544 public void close() {
549 } catch (Exception e) {
554 * Private method to close the connection.
556 private void close2() {
557 synchronized (this) {
558 LOGGER.debug("close2()");
559 boolean notifyHandler = onlineState == State.ACTIVE && !closing;
560 onlineState = State.CLOSED;
561 synchronized (fatalErrorTasks) {
562 fatalErrorTasks.values().forEach(task -> cancelTask(task, true));
563 fatalErrorTasks.clear();
565 cancelTask(checkAliveTask, true);
566 checkAliveTask = null;
569 bridgeHandler.onConnectionOffline();
575 * Close the HTTP 2 session if necessary.
577 private void closeSession() {
578 LOGGER.debug("closeSession()");
579 Session session = http2Session;
580 if (Objects.nonNull(session) && !session.isClosed()) {
581 session.close(0, null, Callback.NOOP);
587 * Method that is called back in case of fatal stream or session events. Note: under normal operation, the Hue
588 * Bridge sends a 'soft' GO_AWAY command every nine or ten hours, so we handle such soft errors by attempting to
589 * silently close and re-open the connection without notifying the handler of an actual 'hard' error.
591 * @param listener the entity that caused this method to be called.
592 * @param cause the exception that caused the error.
594 private synchronized void fatalError(Object listener, Http2Exception cause) {
595 if (onlineState == State.CLOSED || closing) {
598 String causeId = listener.getClass().getSimpleName();
599 if (listener instanceof ContentStreamListenerAdapter) {
600 // on GET / PUT requests the caller handles errors and closes the stream; the session is still OK
601 LOGGER.debug("fatalError() {} {} ignoring", causeId, cause.error);
603 if (LOGGER.isDebugEnabled()) {
604 LOGGER.debug("fatalError() {} {} closing", causeId, cause.error, cause);
606 LOGGER.warn("Fatal error {} {} => closing session.", causeId, cause.error);
613 * Method that is called back in case of fatal stream or session events. Schedules fatalError() to be called after a
614 * delay in order to prevent sequencing issues.
616 * @param listener the entity that caused this method to be called.
617 * @param cause the exception that caused the error.
619 protected void fatalErrorDelayed(Object listener, Http2Exception cause) {
620 synchronized (fatalErrorTasks) {
621 final int index = fatalErrorTasks.size();
622 fatalErrorTasks.put(index, bridgeHandler.getScheduler().schedule(() -> {
623 fatalError(listener, cause);
624 fatalErrorTasks.remove(index);
625 }, 1, TimeUnit.SECONDS));
630 * HTTP GET a Resources object, for a given resource Reference, from the Hue Bridge. The reference is a class
631 * comprising a resource type and an id. If the id is a specific resource id then only the one specific resource
632 * is returned, whereas if it is null then all resources of the given resource type are returned.
634 * It wraps the getResourcesImpl() method in a try/catch block, and transposes any HttpUnAuthorizedException into an
635 * ApiException. Such transposition should never be required in reality since by the time this method is called, the
636 * connection will surely already have been authorised.
638 * @param reference the Reference class to get.
639 * @return a Resource object containing either a list of Resources or a list of Errors.
640 * @throws ApiException if anything fails.
641 * @throws InterruptedException
643 public Resources getResources(ResourceReference reference) throws ApiException, InterruptedException {
644 if (onlineState == State.CLOSED) {
645 throw new ApiException("getResources() offline");
647 return getResourcesImpl(reference);
651 * Internal method to send an HTTP 2 GET request to the Hue Bridge and process its response.
653 * @param reference the Reference class to get.
654 * @return a Resource object containing either a list of Resources or a list of Errors.
655 * @throws HttpUnauthorizedException if the request was refused as not authorised or forbidden.
656 * @throws ApiException if the communication failed, or an unexpected result occurred.
657 * @throws InterruptedException
659 private Resources getResourcesImpl(ResourceReference reference)
660 throws HttpUnauthorizedException, ApiException, InterruptedException {
661 Session session = http2Session;
662 if (Objects.isNull(session) || session.isClosed()) {
663 throw new ApiException("HTTP 2 session is null or closed");
666 String url = getUrl(reference);
667 HeadersFrame headers = prepareHeaders(url, MediaType.APPLICATION_JSON);
668 LOGGER.trace("GET {} HTTP/2", url);
670 Completable<@Nullable Stream> streamPromise = new Completable<>();
671 ContentStreamListenerAdapter contentStreamListener = new ContentStreamListenerAdapter();
672 session.newStream(headers, streamPromise, contentStreamListener);
673 // wait for stream to be opened
674 Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
675 // wait for HTTP response contents
676 String contentJson = contentStreamListener.awaitResult();
677 String contentType = contentStreamListener.getContentType();
678 LOGGER.trace("HTTP/2 200 OK (Content-Type: {}) << {}", contentType, contentJson);
679 if (!MediaType.APPLICATION_JSON.equals(contentType)) {
680 throw new ApiException("Unexpected Content-Type: " + contentType);
683 Resources resources = Objects.requireNonNull(jsonParser.fromJson(contentJson, Resources.class));
684 if (LOGGER.isDebugEnabled()) {
685 resources.getErrors().forEach(error -> LOGGER.debug("Resources error:{}", error));
688 } catch (JsonParseException e) {
689 throw new ApiException("Parsing error", e);
691 } catch (ExecutionException e) {
692 Throwable cause = e.getCause();
693 if (cause instanceof HttpUnauthorizedException) {
694 throw (HttpUnauthorizedException) cause;
696 throw new ApiException("Error sending request", e);
697 } catch (TimeoutException e) {
698 throw new ApiException("Error sending request", e);
705 * Build a full path to a server end point, based on a Reference class instance. If the reference contains only
706 * a resource type, the method returns the end point url to get all resources of the given resource type. Whereas if
707 * it also contains an id, the method returns the end point url to get the specific single resource with that type
710 * @param reference a Reference class instance.
711 * @return the complete end point url.
713 private String getUrl(ResourceReference reference) {
714 String url = baseUrl + reference.getType().name().toLowerCase();
715 String id = reference.getId();
716 return Objects.isNull(id) || id.isEmpty() ? url : url + "/" + id;
720 * The event stream calls this method when it has received text data. It parses the text as JSON into a list of
721 * Event entries, converts the list of events to a list of resources, and forwards that list to the bridge
724 * @param data the incoming (presumed to be JSON) text.
726 protected void onEventData(String data) {
727 if (onlineState != State.ACTIVE) {
730 if (LOGGER.isTraceEnabled()) {
731 LOGGER.trace("onEventData() data:{}", data);
733 LOGGER.debug("onEventData() data length:{}", data.length());
735 JsonElement jsonElement;
737 jsonElement = JsonParser.parseString(data);
738 } catch (JsonSyntaxException e) {
739 LOGGER.debug("onEventData() invalid data '{}'", data, e);
742 if (!(jsonElement instanceof JsonArray)) {
743 LOGGER.debug("onEventData() data is not a JsonArray {}", data);
748 events = jsonParser.fromJson(jsonElement, Event.EVENT_LIST_TYPE);
749 } catch (JsonParseException e) {
750 LOGGER.debug("onEventData() parsing error json:{}", data, e);
753 if (Objects.isNull(events) || events.isEmpty()) {
754 LOGGER.debug("onEventData() event list is null or empty");
757 List<Resource> resources = new ArrayList<>();
758 events.forEach(event -> resources.addAll(event.getData()));
759 if (resources.isEmpty()) {
760 LOGGER.debug("onEventData() resource list is empty");
763 resources.forEach(resource -> resource.markAsSparse());
764 bridgeHandler.onResourcesEvent(resources);
768 * Open the HTTP 2 session and the event stream.
770 * @throws ApiException if there was a communication error.
771 * @throws InterruptedException
773 public void open() throws ApiException, InterruptedException {
774 LOGGER.debug("open()");
777 bridgeHandler.onConnectionOnline();
781 * Make the session active, by opening an HTTP 2 SSE event stream (if necessary).
783 * @throws ApiException if an error was encountered.
784 * @throws InterruptedException
786 private void openActive() throws ApiException, InterruptedException {
787 synchronized (this) {
789 onlineState = State.ACTIVE;
794 * Open the check alive task if necessary.
796 private void openCheckAliveTask() {
797 Future<?> task = checkAliveTask;
798 if (Objects.isNull(task) || task.isCancelled() || task.isDone()) {
799 LOGGER.debug("openCheckAliveTask()");
800 cancelTask(checkAliveTask, false);
801 checkAliveTask = bridgeHandler.getScheduler().scheduleWithFixedDelay(() -> checkAlive(),
802 CHECK_ALIVE_SECONDS, CHECK_ALIVE_SECONDS, TimeUnit.SECONDS);
807 * Implementation to open an HTTP 2 SSE event stream if necessary.
809 * @throws ApiException if an error was encountered.
810 * @throws InterruptedException
812 private void openEventStream() throws ApiException, InterruptedException {
813 Session session = http2Session;
814 if (Objects.isNull(session) || session.isClosed()) {
815 throw new ApiException("HTTP 2 session is null or closed");
817 if (session.getStreams().stream().anyMatch(stream -> Objects.nonNull(stream.getAttribute(EVENT_STREAM_ID)))) {
820 LOGGER.debug("openEventStream()");
821 HeadersFrame headers = prepareHeaders(eventUrl, MediaType.SERVER_SENT_EVENTS);
822 LOGGER.trace("GET {} HTTP/2", eventUrl);
823 Stream stream = null;
825 Completable<@Nullable Stream> streamPromise = new Completable<>();
826 EventStreamListenerAdapter eventStreamListener = new EventStreamListenerAdapter();
827 session.newStream(headers, streamPromise, eventStreamListener);
828 // wait for stream to be opened
829 stream = Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
830 stream.setIdleTimeout(0);
831 stream.setAttribute(EVENT_STREAM_ID, session);
832 // wait for "hi" from the bridge
833 eventStreamListener.awaitResult();
834 } catch (ExecutionException | TimeoutException e) {
835 if (Objects.nonNull(stream)) {
836 stream.reset(new ResetFrame(stream.getId(), 0), Callback.NOOP);
838 throw new ApiException("Error opening event stream", e);
843 * Private method to open the HTTP 2 session in passive mode.
845 * @throws ApiException if there was a communication error.
846 * @throws InterruptedException
848 private void openPassive() throws ApiException, InterruptedException {
849 synchronized (this) {
850 LOGGER.debug("openPassive()");
851 onlineState = State.CLOSED;
853 openCheckAliveTask();
854 onlineState = State.PASSIVE;
859 * Open the HTTP 2 session if necessary.
861 * @throws ApiException if it was not possible to create and connect the session.
862 * @throws InterruptedException
864 private void openSession() throws ApiException, InterruptedException {
865 Session session = http2Session;
866 if (Objects.nonNull(session) && !session.isClosed()) {
869 LOGGER.debug("openSession()");
870 InetSocketAddress address = new InetSocketAddress(hostName, 443);
872 SessionListenerAdapter sessionListener = new SessionListenerAdapter();
873 Completable<@Nullable Session> sessionPromise = new Completable<>();
874 http2Client.connect(http2Client.getBean(SslContextFactory.class), address, sessionListener, sessionPromise);
875 // wait for the (SSL) session to be opened
876 http2Session = Objects.requireNonNull(sessionPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
877 checkAliveOk(); // initialise the session timeout window
878 } catch (ExecutionException | TimeoutException e) {
879 throw new ApiException("Error opening HTTP 2 session", e);
884 * Helper class to create a HeadersFrame for a standard HTTP GET request.
886 * @param url the server url.
887 * @param acceptContentType the accepted content type for the response.
888 * @return the HeadersFrame.
890 private HeadersFrame prepareHeaders(String url, String acceptContentType) {
891 return prepareHeaders(url, acceptContentType, "GET", -1, null);
895 * Helper class to create a HeadersFrame for a more exotic HTTP request.
897 * @param url the server url.
898 * @param acceptContentType the accepted content type for the response.
899 * @param method the HTTP request method.
900 * @param contentLength the length of the content e.g. for a PUT call.
901 * @param contentType the respective content type.
902 * @return the HeadersFrame.
904 private HeadersFrame prepareHeaders(String url, String acceptContentType, String method, long contentLength,
905 @Nullable String contentType) {
906 HttpFields fields = new HttpFields();
907 fields.put(HttpHeader.ACCEPT, acceptContentType);
908 if (contentType != null) {
909 fields.put(HttpHeader.CONTENT_TYPE, contentType);
911 if (contentLength >= 0) {
912 fields.putLongField(HttpHeader.CONTENT_LENGTH, contentLength);
914 fields.put(APPLICATION_KEY, applicationKey);
915 return new HeadersFrame(new MetaData.Request(method, new HttpURI(url), HttpVersion.HTTP_2, fields), null,
920 * Use an HTTP/2 PUT command to send a resource to the server. Note: the Hue bridge server can sometimes get
921 * confused by parallel PUT commands, so use 'synchronized' to prevent that.
923 * @param resource the resource to put.
924 * @throws ApiException if something fails.
925 * @throws InterruptedException
927 public synchronized void putResource(Resource resource) throws ApiException, InterruptedException {
928 if (onlineState == State.CLOSED) {
931 Session session = http2Session;
932 if (Objects.isNull(session) || session.isClosed()) {
933 throw new ApiException("HTTP 2 session is null or closed");
936 String requestJson = jsonParser.toJson(resource);
937 ByteBuffer requestBytes = ByteBuffer.wrap(requestJson.getBytes(StandardCharsets.UTF_8));
938 String url = getUrl(new ResourceReference().setId(resource.getId()).setType(resource.getType()));
939 HeadersFrame headers = prepareHeaders(url, MediaType.APPLICATION_JSON, "PUT", requestBytes.capacity(),
940 MediaType.APPLICATION_JSON);
941 LOGGER.trace("PUT {} HTTP/2 >> {}", url, requestJson);
943 Completable<@Nullable Stream> streamPromise = new Completable<>();
944 ContentStreamListenerAdapter contentStreamListener = new ContentStreamListenerAdapter();
945 session.newStream(headers, streamPromise, contentStreamListener);
946 // wait for stream to be opened
947 Stream stream = Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
948 stream.data(new DataFrame(stream.getId(), requestBytes, true), Callback.NOOP);
949 // wait for HTTP response
950 String contentJson = contentStreamListener.awaitResult();
951 String contentType = contentStreamListener.getContentType();
952 LOGGER.trace("HTTP/2 200 OK (Content-Type: {}) << {}", contentType, contentJson);
953 if (!MediaType.APPLICATION_JSON.equals(contentType)) {
954 throw new ApiException("Unexpected Content-Type: " + contentType);
957 Resources resources = Objects.requireNonNull(jsonParser.fromJson(contentJson, Resources.class));
958 if (LOGGER.isDebugEnabled()) {
959 resources.getErrors().forEach(error -> LOGGER.debug("putResource() resources error:{}", error));
961 } catch (JsonParseException e) {
962 LOGGER.debug("putResource() parsing error json:{}", contentJson, e);
963 throw new ApiException("Parsing error", e);
965 } catch (ExecutionException | TimeoutException e) {
966 throw new ApiException("putResource() error sending request", e);
973 * Try to register the application key with the hub. Use the given application key if one is provided; otherwise the
974 * hub will create a new one. Note: this requires an HTTP 1.1 client call.
976 * @param oldApplicationKey existing application key if any i.e. may be empty.
977 * @return the existing or a newly created application key.
978 * @throws HttpUnauthorizedException if the registration failed.
979 * @throws ApiException if there was a communications error.
980 * @throws InterruptedException
982 public String registerApplicationKey(@Nullable String oldApplicationKey)
983 throws HttpUnauthorizedException, ApiException, InterruptedException {
984 LOGGER.debug("registerApplicationKey()");
985 String json = jsonParser.toJson((Objects.isNull(oldApplicationKey) || oldApplicationKey.isEmpty())
986 ? new CreateUserRequest(APPLICATION_ID)
987 : new CreateUserRequest(oldApplicationKey, APPLICATION_ID));
988 Request httpRequest = httpClient.newRequest(registrationUrl).method(HttpMethod.POST)
989 .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
990 .content(new StringContentProvider(json), MediaType.APPLICATION_JSON);
991 ContentResponse contentResponse;
993 LOGGER.trace("POST {} HTTP/1.1 >> {}", registrationUrl, json);
994 contentResponse = httpRequest.send();
995 } catch (TimeoutException | ExecutionException e) {
996 throw new ApiException("HTTP processing error", e);
998 int httpStatus = contentResponse.getStatus();
999 json = contentResponse.getContentAsString().trim();
1000 LOGGER.trace("HTTP/1.1 {} {} << {}", httpStatus, contentResponse.getReason(), json);
1001 if (httpStatus != HttpStatus.OK_200) {
1002 throw new ApiException("HTTP bad response");
1005 List<SuccessResponse> entries = jsonParser.fromJson(json, SuccessResponse.GSON_TYPE);
1006 if (Objects.nonNull(entries) && !entries.isEmpty()) {
1007 SuccessResponse response = entries.get(0);
1008 Map<String, Object> responseSuccess = response.success;
1009 if (Objects.nonNull(responseSuccess)) {
1010 String newApplicationKey = (String) responseSuccess.get("username");
1011 if (Objects.nonNull(newApplicationKey)) {
1012 return newApplicationKey;
1016 } catch (JsonParseException e) {
1017 LOGGER.debug("registerApplicationKey() parsing error json:{}", json, e);
1019 throw new HttpUnauthorizedException("Application key registration failed");
1023 * Test the Hue Bridge connection state by attempting to connect and trying to execute a basic command that requires
1026 * @throws HttpUnauthorizedException if it was possible to connect but not to authenticate.
1027 * @throws ApiException if it was not possible to connect.
1028 * @throws InterruptedException
1030 public void testConnectionState() throws HttpUnauthorizedException, ApiException, InterruptedException {
1031 LOGGER.debug("testConnectionState()");
1034 getResourcesImpl(BRIDGE);
1035 } catch (ApiException e) {
1042 * Hue Bridges get confused if they receive too many HTTP requests in a short period of time (e.g. on start up), or
1043 * if too many HTTP sessions are opened at the same time. So this method throttles the requests to a maximum of one
1044 * per REQUEST_INTERVAL_MILLISECS, and ensures that no more than MAX_CONCURRENT_SESSIONS sessions are started.
1046 * @throws InterruptedException
1048 private synchronized void throttle() throws InterruptedException {
1049 streamMutex.acquire();
1050 Instant now = Instant.now();
1051 if (lastRequestTime.isPresent()) {
1052 long delay = Duration.between(now, lastRequestTime.get()).toMillis() + REQUEST_INTERVAL_MILLISECS;
1054 Thread.sleep(delay);
1057 lastRequestTime = Optional.of(now);
1061 * Release the mutex.
1063 private void throttleDone() {
1064 streamMutex.release();