]> git.basschouten.com Git - openhab-addons.git/blob
009835eae3275a45b10881678545c6d2ca1b26b0
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 Contributors to the openHAB project
3  *
4  * See the NOTICE file(s) distributed with this work for additional
5  * information.
6  *
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
10  *
11  * SPDX-License-Identifier: EPL-2.0
12  */
13 package org.openhab.binding.hue.internal.connection;
14
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;
29 import java.util.Map;
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;
41
42 import javax.ws.rs.core.MediaType;
43
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;
84
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;
91
92 /**
93  * This class handles HTTP and SSE connections to/from a Hue Bridge running CLIP 2.
94  *
95  * It uses the following connection mechanisms:
96  *
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>
100  *
101  * @author Andrew Fiddian-Green - Initial Contribution
102  */
103 @NonNullByDefault
104 public class Clip2Bridge implements Closeable {
105
106     /**
107      * Base (abstract) adapter for listening to HTTP 2 stream events.
108      *
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.
111      *
112      * It handles the following fatal error events by notifying the containing class:
113      *
114      * <li>onHeaders() HTTP unauthorized codes</li>
115      */
116     private abstract class BaseStreamListenerAdapter<T> extends Stream.Listener.Adapter {
117         protected final CompletableFuture<T> completable = new CompletableFuture<T>();
118         private String contentType = "UNDEFINED";
119
120         protected T awaitResult() throws ExecutionException, InterruptedException, TimeoutException {
121             return completable.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
122         }
123
124         /**
125          * Return the HTTP content type.
126          *
127          * @return content type e.g. 'application/json'
128          */
129         protected String getContentType() {
130             return contentType;
131         }
132
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"));
138             } else {
139                 completable.completeExceptionally(e);
140             }
141             fatalErrorDelayed(this, e);
142         }
143
144         /**
145          * Check the reply headers to see whether the request was authorised.
146          */
147         @Override
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);
158                     default:
159                 }
160                 contentType = responseMetaData.getFields().get(HttpHeader.CONTENT_TYPE).toLowerCase();
161             }
162         }
163     }
164
165     /**
166      * Adapter for listening to regular HTTP 2 GET/PUT request stream events.
167      *
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.
170      *
171      * In addition to those handled by the parent, it handles the following fatal error events by notifying the
172      * containing class:
173      *
174      * <li>onIdleTimeout()</li>
175      * <li>onTimeout()</li>
176      */
177     private class ContentStreamListenerAdapter extends BaseStreamListenerAdapter<String> {
178         private final DataFrameCollector content = new DataFrameCollector();
179
180         @Override
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());
188                     content.reset();
189                 }
190             }
191             callback.succeeded();
192         }
193
194         @Override
195         public boolean onIdleTimeout(@Nullable Stream stream, @Nullable Throwable x) {
196             handleHttp2Error(Http2Error.IDLE);
197             return true;
198         }
199
200         @Override
201         public void onTimeout(@Nullable Stream stream, @Nullable Throwable x) {
202             handleHttp2Error(Http2Error.TIMEOUT);
203         }
204     }
205
206     /**
207      * Class to collect incoming ByteBuffer data from HTTP 2 Data frames.
208      */
209     private static class DataFrameCollector {
210         private byte[] buffer = new byte[512];
211         private int usedSize = 0;
212
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);
219             }
220             data.get(buffer, usedSize, dataCapacity);
221             usedSize += dataCapacity;
222         }
223
224         public String contentAsString() {
225             return new String(buffer, 0, usedSize, StandardCharsets.UTF_8);
226         }
227
228         public Reader contentStreamReader() {
229             return new InputStreamReader(new ByteArrayInputStream(buffer, 0, usedSize), StandardCharsets.UTF_8);
230         }
231
232         public void reset() {
233             usedSize = 0;
234         }
235     }
236
237     /**
238      * Adapter for listening to SSE event stream events.
239      *
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.
244      *
245      * The stream must be permanently connected, so it ignores onIdleTimeout() events.
246      *
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:
249      *
250      * <li>onClosed()</li>
251      * <li>onReset()</li>
252      */
253     private class EventStreamListenerAdapter extends BaseStreamListenerAdapter<Boolean> {
254         private final DataFrameCollector eventData = new DataFrameCollector();
255
256         @Override
257         public void onClosed(@Nullable Stream stream) {
258             handleHttp2Error(Http2Error.CLOSED);
259         }
260
261         @Override
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());
270
271                 // a blank line marks the end of an SSE message
272                 boolean endOfMessage = !receivedLines.isEmpty()
273                         && receivedLines.get(receivedLines.size() - 1).isBlank();
274
275                 if (endOfMessage) {
276                     eventData.reset();
277                     // receipt of ANY message means the event stream is established
278                     if (!completable.isDone()) {
279                         completable.complete(Boolean.TRUE);
280                     }
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());
286                         }
287                     }
288                     if (eventContent.length() > 0) {
289                         onEventData(eventContent.toString().trim());
290                     }
291                 }
292             }
293             callback.succeeded();
294         }
295
296         @Override
297         public boolean onIdleTimeout(@Nullable Stream stream, @Nullable Throwable x) {
298             return false;
299         }
300
301         @Override
302         public void onReset(@Nullable Stream stream, @Nullable ResetFrame frame) {
303             handleHttp2Error(Http2Error.RESET);
304         }
305     }
306
307     /**
308      * Enum of potential fatal HTTP 2 session/stream errors.
309      */
310     private enum Http2Error {
311         CLOSED,
312         FAILURE,
313         TIMEOUT,
314         RESET,
315         IDLE,
316         GO_AWAY,
317         UNAUTHORIZED;
318     }
319
320     /**
321      * Private exception for handling HTTP 2 stream and session errors.
322      */
323     @SuppressWarnings("serial")
324     private static class Http2Exception extends ApiException {
325         public final Http2Error error;
326
327         public Http2Exception(Http2Error error) {
328             this(error, null);
329         }
330
331         public Http2Exception(Http2Error error, @Nullable Throwable cause) {
332             super("HTTP 2 stream " + error.toString().toLowerCase(), cause);
333             this.error = error;
334         }
335     }
336
337     /**
338      * Adapter for listening to HTTP 2 session status events.
339      *
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:
342      *
343      * <li>onClose()</li>
344      * <li>onFailure()</li>
345      * <li>onGoAway()</li>
346      * <li>onReset()</li>
347      */
348     private class SessionListenerAdapter extends Session.Listener.Adapter {
349
350         @Override
351         public void onClose(@Nullable Session session, @Nullable GoAwayFrame frame) {
352             fatalErrorDelayed(this, new Http2Exception(Http2Error.CLOSED));
353         }
354
355         @Override
356         public void onFailure(@Nullable Session session, @Nullable Throwable failure) {
357             fatalErrorDelayed(this, new Http2Exception(Http2Error.FAILURE));
358         }
359
360         @Override
361         public void onGoAway(@Nullable Session session, @Nullable GoAwayFrame frame) {
362             fatalErrorDelayed(this, new Http2Exception(Http2Error.GO_AWAY));
363         }
364
365         @Override
366         public boolean onIdleTimeout(@Nullable Session session) {
367             return false;
368         }
369
370         @Override
371         public void onPing(@Nullable Session session, @Nullable PingFrame frame) {
372             checkAliveOk();
373             if (Objects.nonNull(session) && Objects.nonNull(frame) && !frame.isReply()) {
374                 session.ping(new PingFrame(true), Callback.NOOP);
375             }
376         }
377
378         @Override
379         public void onReset(@Nullable Session session, @Nullable ResetFrame frame) {
380             fatalErrorDelayed(this, new Http2Exception(Http2Error.RESET));
381         }
382     }
383
384     /**
385      * Enum showing the online state of the session connection.
386      */
387     private static enum State {
388         /**
389          * Session closed
390          */
391         CLOSED,
392         /**
393          * Session open for HTTP calls only
394          */
395         PASSIVE,
396         /**
397          * Session open for HTTP calls and actively receiving SSE events
398          */
399         ACTIVE;
400     }
401
402     /**
403      * Class for throttling HTTP GET and PUT requests to prevent overloading the Hue bridge.
404      * <p>
405      * The Hue Bridge can get confused if they receive too many HTTP requests in a short period of time (e.g. on start
406      * up), or if too many HTTP sessions are opened at the same time, which cause it to respond with an HTML error page.
407      * So this class a) waits to acquire permitCount (or no more than MAX_CONCURRENT_SESSIONS) stream permits, and b)
408      * throttles the requests to a maximum of one per REQUEST_INTERVAL_MILLISECS.
409      */
410     private class Throttler implements AutoCloseable {
411         private final int permitCount;
412
413         /**
414          * @param permitCount indicates how many stream permits to be acquired.
415          * @throws InterruptedException
416          */
417         Throttler(int permitCount) throws InterruptedException {
418             this.permitCount = permitCount;
419             streamMutex.acquire(permitCount);
420             long delay;
421             synchronized (Clip2Bridge.this) {
422                 Instant now = Instant.now();
423                 delay = lastRequestTime
424                         .map(t -> Math.max(0, Duration.between(now, t).toMillis() + REQUEST_INTERVAL_MILLISECS))
425                         .orElse(0L);
426                 lastRequestTime = Optional.of(now.plusMillis(delay));
427             }
428             Thread.sleep(delay);
429         }
430
431         @Override
432         public void close() {
433             streamMutex.release(permitCount);
434         }
435     }
436
437     private static final Logger LOGGER = LoggerFactory.getLogger(Clip2Bridge.class);
438
439     private static final String APPLICATION_ID = "org-openhab-binding-hue-clip2";
440     private static final String APPLICATION_KEY = "hue-application-key";
441
442     private static final String EVENT_STREAM_ID = "eventStream";
443     private static final String FORMAT_URL_CONFIG = "http://%s/api/0/config";
444     private static final String FORMAT_URL_RESOURCE = "https://%s/clip/v2/resource/";
445     private static final String FORMAT_URL_REGISTER = "http://%s/api";
446     private static final String FORMAT_URL_EVENTS = "https://%s/eventstream/clip/v2";
447
448     private static final long CLIP2_MINIMUM_VERSION = 1948086000L;
449
450     public static final int TIMEOUT_SECONDS = 10;
451     private static final int CHECK_ALIVE_SECONDS = 300;
452     private static final int REQUEST_INTERVAL_MILLISECS = 50;
453     private static final int MAX_CONCURRENT_STREAMS = 3;
454
455     private static final ResourceReference BRIDGE = new ResourceReference().setType(ResourceType.BRIDGE);
456
457     /**
458      * Static method to attempt to connect to a Hue Bridge, get its software version, and check if it is high enough to
459      * support the CLIP 2 API.
460      *
461      * @param hostName the bridge IP address.
462      * @return true if bridge is online and it supports CLIP 2, or false if it is online and does not support CLIP 2.
463      * @throws IOException if unable to communicate with the bridge.
464      * @throws NumberFormatException if the bridge firmware version is invalid.
465      */
466     public static boolean isClip2Supported(String hostName) throws IOException {
467         String response;
468         Properties headers = new Properties();
469         headers.put(HttpHeader.ACCEPT, MediaType.APPLICATION_JSON);
470         response = HttpUtil.executeUrl("GET", String.format(FORMAT_URL_CONFIG, hostName), headers, null, null,
471                 TIMEOUT_SECONDS * 1000);
472         BridgeConfig config = new Gson().fromJson(response, BridgeConfig.class);
473         if (Objects.nonNull(config)) {
474             String swVersion = config.swversion;
475             if (Objects.nonNull(swVersion)) {
476                 try {
477                     if (Long.parseLong(swVersion) >= CLIP2_MINIMUM_VERSION) {
478                         return true;
479                     }
480                 } catch (NumberFormatException e) {
481                     LOGGER.debug("isClip2Supported() swVersion '{}' is not a number", swVersion);
482                 }
483             }
484         }
485         return false;
486     }
487
488     private final HttpClient httpClient;
489     private final HTTP2Client http2Client;
490     private final String hostName;
491     private final String baseUrl;
492     private final String eventUrl;
493     private final String registrationUrl;
494     private final String applicationKey;
495     private final Clip2BridgeHandler bridgeHandler;
496     private final Gson jsonParser = new Gson();
497     private final Semaphore streamMutex = new Semaphore(MAX_CONCURRENT_STREAMS, true);
498
499     private boolean closing;
500     private State onlineState = State.CLOSED;
501     private Optional<Instant> lastRequestTime = Optional.empty();
502     private Instant sessionExpireTime = Instant.MAX;
503     private @Nullable Session http2Session;
504
505     private @Nullable Future<?> checkAliveTask;
506     private Map<Integer, Future<?>> fatalErrorTasks = new ConcurrentHashMap<>();
507
508     /**
509      * Constructor.
510      *
511      * @param httpClientFactory the OH core HttpClientFactory.
512      * @param bridgeHandler the bridge handler.
513      * @param hostName the host name (ip address) of the Hue bridge
514      * @param applicationKey the application key.
515      * @throws ApiException if unable to open Jetty HTTP/2 client.
516      */
517     public Clip2Bridge(HttpClientFactory httpClientFactory, Clip2BridgeHandler bridgeHandler, String hostName,
518             String applicationKey) throws ApiException {
519         LOGGER.debug("Clip2Bridge()");
520         httpClient = httpClientFactory.getCommonHttpClient();
521         http2Client = httpClientFactory.createHttp2Client("hue-clip2", httpClient.getSslContextFactory());
522         http2Client.setConnectTimeout(Clip2Bridge.TIMEOUT_SECONDS * 1000);
523         http2Client.setIdleTimeout(-1);
524         try {
525             http2Client.start();
526         } catch (Exception e) {
527             throw new ApiException("Error starting HTTP/2 client", e);
528         }
529         this.bridgeHandler = bridgeHandler;
530         this.hostName = hostName;
531         this.applicationKey = applicationKey;
532         baseUrl = String.format(FORMAT_URL_RESOURCE, hostName);
533         eventUrl = String.format(FORMAT_URL_EVENTS, hostName);
534         registrationUrl = String.format(FORMAT_URL_REGISTER, hostName);
535     }
536
537     /**
538      * Cancel the given task.
539      *
540      * @param cancelTask the task to be cancelled (may be null)
541      * @param mayInterrupt allows cancel() to interrupt the thread.
542      */
543     private void cancelTask(@Nullable Future<?> cancelTask, boolean mayInterrupt) {
544         if (Objects.nonNull(cancelTask)) {
545             cancelTask.cancel(mayInterrupt);
546         }
547     }
548
549     /**
550      * Send a ping to the Hue bridge to check that the session is still alive.
551      */
552     private void checkAlive() {
553         if (onlineState == State.CLOSED) {
554             return;
555         }
556         LOGGER.debug("checkAlive()");
557         Session session = http2Session;
558         if (Objects.nonNull(session)) {
559             session.ping(new PingFrame(false), Callback.NOOP);
560         }
561         if (Instant.now().isAfter(sessionExpireTime)) {
562             fatalError(this, new Http2Exception(Http2Error.TIMEOUT));
563         }
564     }
565
566     /**
567      * Connection is ok, so reschedule the session check alive expire time. Called in response to incoming ping frames
568      * from the bridge.
569      */
570     protected void checkAliveOk() {
571         LOGGER.debug("checkAliveOk()");
572         sessionExpireTime = Instant.now().plusSeconds(CHECK_ALIVE_SECONDS * 2);
573     }
574
575     /**
576      * Close the connection.
577      */
578     @Override
579     public void close() {
580         closing = true;
581         close2();
582         try {
583             http2Client.stop();
584         } catch (Exception e) {
585         }
586     }
587
588     /**
589      * Private method to close the connection.
590      */
591     private void close2() {
592         synchronized (this) {
593             LOGGER.debug("close2()");
594             boolean notifyHandler = onlineState == State.ACTIVE && !closing;
595             onlineState = State.CLOSED;
596             synchronized (fatalErrorTasks) {
597                 fatalErrorTasks.values().forEach(task -> cancelTask(task, true));
598                 fatalErrorTasks.clear();
599             }
600             cancelTask(checkAliveTask, true);
601             checkAliveTask = null;
602             closeSession();
603             if (notifyHandler) {
604                 bridgeHandler.onConnectionOffline();
605             }
606         }
607     }
608
609     /**
610      * Close the HTTP 2 session if necessary.
611      */
612     private void closeSession() {
613         LOGGER.debug("closeSession()");
614         Session session = http2Session;
615         if (Objects.nonNull(session) && !session.isClosed()) {
616             session.close(0, null, Callback.NOOP);
617         }
618         http2Session = null;
619     }
620
621     /**
622      * Method that is called back in case of fatal stream or session events. Note: under normal operation, the Hue
623      * Bridge sends a 'soft' GO_AWAY command every nine or ten hours, so we handle such soft errors by attempting to
624      * silently close and re-open the connection without notifying the handler of an actual 'hard' error.
625      *
626      * @param listener the entity that caused this method to be called.
627      * @param cause the exception that caused the error.
628      */
629     private synchronized void fatalError(Object listener, Http2Exception cause) {
630         if (onlineState == State.CLOSED || closing) {
631             return;
632         }
633         String causeId = listener.getClass().getSimpleName();
634         if (listener instanceof ContentStreamListenerAdapter) {
635             // on GET / PUT requests the caller handles errors and closes the stream; the session is still OK
636             LOGGER.debug("fatalError() {} {} ignoring", causeId, cause.error);
637         } else {
638             if (LOGGER.isDebugEnabled()) {
639                 LOGGER.debug("fatalError() {} {} closing", causeId, cause.error, cause);
640             } else {
641                 LOGGER.warn("Fatal error {} {} => closing session.", causeId, cause.error);
642             }
643             close2();
644         }
645     }
646
647     /**
648      * Method that is called back in case of fatal stream or session events. Schedules fatalError() to be called after a
649      * delay in order to prevent sequencing issues.
650      *
651      * @param listener the entity that caused this method to be called.
652      * @param cause the exception that caused the error.
653      */
654     protected void fatalErrorDelayed(Object listener, Http2Exception cause) {
655         synchronized (fatalErrorTasks) {
656             final int index = fatalErrorTasks.size();
657             fatalErrorTasks.put(index, bridgeHandler.getScheduler().schedule(() -> {
658                 fatalError(listener, cause);
659                 fatalErrorTasks.remove(index);
660             }, 1, TimeUnit.SECONDS));
661         }
662     }
663
664     /**
665      * HTTP GET a Resources object, for a given resource Reference, from the Hue Bridge. The reference is a class
666      * comprising a resource type and an id. If the id is a specific resource id then only the one specific resource
667      * is returned, whereas if it is null then all resources of the given resource type are returned.
668      *
669      * It wraps the getResourcesImpl() method in a try/catch block, and transposes any HttpUnAuthorizedException into an
670      * ApiException. Such transposition should never be required in reality since by the time this method is called, the
671      * connection will surely already have been authorised.
672      *
673      * @param reference the Reference class to get.
674      * @return a Resource object containing either a list of Resources or a list of Errors.
675      * @throws ApiException if anything fails.
676      * @throws InterruptedException
677      */
678     public Resources getResources(ResourceReference reference) throws ApiException, InterruptedException {
679         if (onlineState == State.CLOSED) {
680             throw new ApiException("getResources() offline");
681         }
682         return getResourcesImpl(reference);
683     }
684
685     /**
686      * Internal method to send an HTTP 2 GET request to the Hue Bridge and process its response.
687      *
688      * @param reference the Reference class to get.
689      * @return a Resource object containing either a list of Resources or a list of Errors.
690      * @throws HttpUnauthorizedException if the request was refused as not authorised or forbidden.
691      * @throws ApiException if the communication failed, or an unexpected result occurred.
692      * @throws InterruptedException
693      */
694     private Resources getResourcesImpl(ResourceReference reference)
695             throws HttpUnauthorizedException, ApiException, InterruptedException {
696         Session session = http2Session;
697         if (Objects.isNull(session) || session.isClosed()) {
698             throw new ApiException("HTTP 2 session is null or closed");
699         }
700         try (Throttler throttler = new Throttler(1)) {
701             String url = getUrl(reference);
702             LOGGER.trace("GET {} HTTP/2", url);
703             HeadersFrame headers = prepareHeaders(url, MediaType.APPLICATION_JSON);
704             Completable<@Nullable Stream> streamPromise = new Completable<>();
705             ContentStreamListenerAdapter contentStreamListener = new ContentStreamListenerAdapter();
706             session.newStream(headers, streamPromise, contentStreamListener);
707             // wait for stream to be opened
708             Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
709             // wait for HTTP response contents
710             String contentJson = contentStreamListener.awaitResult();
711             String contentType = contentStreamListener.getContentType();
712             LOGGER.trace("HTTP/2 200 OK (Content-Type: {}) << {}", contentType, contentJson);
713             if (!MediaType.APPLICATION_JSON.equals(contentType)) {
714                 throw new ApiException("Unexpected Content-Type: " + contentType);
715             }
716             try {
717                 Resources resources = Objects.requireNonNull(jsonParser.fromJson(contentJson, Resources.class));
718                 if (LOGGER.isDebugEnabled()) {
719                     resources.getErrors().forEach(error -> LOGGER.debug("Resources error:{}", error));
720                 }
721                 return resources;
722             } catch (JsonParseException e) {
723                 throw new ApiException("Parsing error", e);
724             }
725         } catch (ExecutionException e) {
726             Throwable cause = e.getCause();
727             if (cause instanceof HttpUnauthorizedException) {
728                 throw (HttpUnauthorizedException) cause;
729             }
730             throw new ApiException("Error sending request", e);
731         } catch (TimeoutException e) {
732             throw new ApiException("Error sending request", e);
733         }
734     }
735
736     /**
737      * Build a full path to a server end point, based on a Reference class instance. If the reference contains only
738      * a resource type, the method returns the end point url to get all resources of the given resource type. Whereas if
739      * it also contains an id, the method returns the end point url to get the specific single resource with that type
740      * and id.
741      *
742      * @param reference a Reference class instance.
743      * @return the complete end point url.
744      */
745     private String getUrl(ResourceReference reference) {
746         String url = baseUrl + reference.getType().name().toLowerCase();
747         String id = reference.getId();
748         return Objects.isNull(id) || id.isEmpty() ? url : url + "/" + id;
749     }
750
751     /**
752      * The event stream calls this method when it has received text data. It parses the text as JSON into a list of
753      * Event entries, converts the list of events to a list of resources, and forwards that list to the bridge
754      * handler.
755      *
756      * @param data the incoming (presumed to be JSON) text.
757      */
758     protected void onEventData(String data) {
759         if (onlineState != State.ACTIVE) {
760             return;
761         }
762         if (LOGGER.isTraceEnabled()) {
763             LOGGER.trace("onEventData() data:{}", data);
764         } else {
765             LOGGER.debug("onEventData() data length:{}", data.length());
766         }
767         JsonElement jsonElement;
768         try {
769             jsonElement = JsonParser.parseString(data);
770         } catch (JsonSyntaxException e) {
771             LOGGER.debug("onEventData() invalid data '{}'", data, e);
772             return;
773         }
774         if (!(jsonElement instanceof JsonArray)) {
775             LOGGER.debug("onEventData() data is not a JsonArray {}", data);
776             return;
777         }
778         List<Event> events;
779         try {
780             events = jsonParser.fromJson(jsonElement, Event.EVENT_LIST_TYPE);
781         } catch (JsonParseException e) {
782             LOGGER.debug("onEventData() parsing error json:{}", data, e);
783             return;
784         }
785         if (Objects.isNull(events) || events.isEmpty()) {
786             LOGGER.debug("onEventData() event list is null or empty");
787             return;
788         }
789         List<Resource> resources = new ArrayList<>();
790         events.forEach(event -> resources.addAll(event.getData()));
791         if (resources.isEmpty()) {
792             LOGGER.debug("onEventData() resource list is empty");
793             return;
794         }
795         resources.forEach(resource -> resource.markAsSparse());
796         bridgeHandler.onResourcesEvent(resources);
797     }
798
799     /**
800      * Open the HTTP 2 session and the event stream.
801      *
802      * @throws ApiException if there was a communication error.
803      * @throws InterruptedException
804      */
805     public void open() throws ApiException, InterruptedException {
806         LOGGER.debug("open()");
807         openPassive();
808         openActive();
809         bridgeHandler.onConnectionOnline();
810     }
811
812     /**
813      * Make the session active, by opening an HTTP 2 SSE event stream (if necessary).
814      *
815      * @throws ApiException if an error was encountered.
816      * @throws InterruptedException
817      */
818     private void openActive() throws ApiException, InterruptedException {
819         synchronized (this) {
820             openEventStream();
821             onlineState = State.ACTIVE;
822         }
823     }
824
825     /**
826      * Open the check alive task if necessary.
827      */
828     private void openCheckAliveTask() {
829         Future<?> task = checkAliveTask;
830         if (Objects.isNull(task) || task.isCancelled() || task.isDone()) {
831             LOGGER.debug("openCheckAliveTask()");
832             cancelTask(checkAliveTask, false);
833             checkAliveTask = bridgeHandler.getScheduler().scheduleWithFixedDelay(() -> checkAlive(),
834                     CHECK_ALIVE_SECONDS, CHECK_ALIVE_SECONDS, TimeUnit.SECONDS);
835         }
836     }
837
838     /**
839      * Implementation to open an HTTP 2 SSE event stream if necessary.
840      *
841      * @throws ApiException if an error was encountered.
842      * @throws InterruptedException
843      */
844     private void openEventStream() throws ApiException, InterruptedException {
845         Session session = http2Session;
846         if (Objects.isNull(session) || session.isClosed()) {
847             throw new ApiException("HTTP 2 session is null or closed");
848         }
849         if (session.getStreams().stream().anyMatch(stream -> Objects.nonNull(stream.getAttribute(EVENT_STREAM_ID)))) {
850             return;
851         }
852         LOGGER.debug("openEventStream()");
853         HeadersFrame headers = prepareHeaders(eventUrl, MediaType.SERVER_SENT_EVENTS);
854         LOGGER.trace("GET {} HTTP/2", eventUrl);
855         Stream stream = null;
856         try {
857             Completable<@Nullable Stream> streamPromise = new Completable<>();
858             EventStreamListenerAdapter eventStreamListener = new EventStreamListenerAdapter();
859             session.newStream(headers, streamPromise, eventStreamListener);
860             // wait for stream to be opened
861             stream = Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
862             stream.setIdleTimeout(0);
863             stream.setAttribute(EVENT_STREAM_ID, session);
864             // wait for "hi" from the bridge
865             eventStreamListener.awaitResult();
866         } catch (ExecutionException | TimeoutException e) {
867             if (Objects.nonNull(stream)) {
868                 stream.reset(new ResetFrame(stream.getId(), 0), Callback.NOOP);
869             }
870             throw new ApiException("Error opening event stream", e);
871         }
872     }
873
874     /**
875      * Private method to open the HTTP 2 session in passive mode.
876      *
877      * @throws ApiException if there was a communication error.
878      * @throws InterruptedException
879      */
880     private void openPassive() throws ApiException, InterruptedException {
881         synchronized (this) {
882             LOGGER.debug("openPassive()");
883             onlineState = State.CLOSED;
884             openSession();
885             openCheckAliveTask();
886             onlineState = State.PASSIVE;
887         }
888     }
889
890     /**
891      * Open the HTTP 2 session if necessary.
892      *
893      * @throws ApiException if it was not possible to create and connect the session.
894      * @throws InterruptedException
895      */
896     private void openSession() throws ApiException, InterruptedException {
897         Session session = http2Session;
898         if (Objects.nonNull(session) && !session.isClosed()) {
899             return;
900         }
901         LOGGER.debug("openSession()");
902         InetSocketAddress address = new InetSocketAddress(hostName, 443);
903         try {
904             SessionListenerAdapter sessionListener = new SessionListenerAdapter();
905             Completable<@Nullable Session> sessionPromise = new Completable<>();
906             http2Client.connect(http2Client.getBean(SslContextFactory.class), address, sessionListener, sessionPromise);
907             // wait for the (SSL) session to be opened
908             http2Session = Objects.requireNonNull(sessionPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
909             checkAliveOk(); // initialise the session timeout window
910         } catch (ExecutionException | TimeoutException e) {
911             throw new ApiException("Error opening HTTP 2 session", e);
912         }
913     }
914
915     /**
916      * Helper class to create a HeadersFrame for a standard HTTP GET request.
917      *
918      * @param url the server url.
919      * @param acceptContentType the accepted content type for the response.
920      * @return the HeadersFrame.
921      */
922     private HeadersFrame prepareHeaders(String url, String acceptContentType) {
923         return prepareHeaders(url, acceptContentType, "GET", -1, null);
924     }
925
926     /**
927      * Helper class to create a HeadersFrame for a more exotic HTTP request.
928      *
929      * @param url the server url.
930      * @param acceptContentType the accepted content type for the response.
931      * @param method the HTTP request method.
932      * @param contentLength the length of the content e.g. for a PUT call.
933      * @param contentType the respective content type.
934      * @return the HeadersFrame.
935      */
936     private HeadersFrame prepareHeaders(String url, String acceptContentType, String method, long contentLength,
937             @Nullable String contentType) {
938         HttpFields fields = new HttpFields();
939         fields.put(HttpHeader.ACCEPT, acceptContentType);
940         if (contentType != null) {
941             fields.put(HttpHeader.CONTENT_TYPE, contentType);
942         }
943         if (contentLength >= 0) {
944             fields.putLongField(HttpHeader.CONTENT_LENGTH, contentLength);
945         }
946         fields.put(APPLICATION_KEY, applicationKey);
947         return new HeadersFrame(new MetaData.Request(method, new HttpURI(url), HttpVersion.HTTP_2, fields), null,
948                 contentLength <= 0);
949     }
950
951     /**
952      * Use an HTTP/2 PUT command to send a resource to the server. Note: the Hue Bridge can get confused by parallel
953      * overlapping PUT resp. GET commands which cause it to respond with an HTML error page. So this method acquires all
954      * of the stream access permits (given by MAX_CONCURRENT_STREAMS) in order to prevent such overlaps.
955      *
956      * @param resource the resource to put.
957      * @throws ApiException if something fails.
958      * @throws InterruptedException
959      */
960     public void putResource(Resource resource) throws ApiException, InterruptedException {
961         if (onlineState == State.CLOSED) {
962             return;
963         }
964         Session session = http2Session;
965         if (Objects.isNull(session) || session.isClosed()) {
966             throw new ApiException("HTTP 2 session is null or closed");
967         }
968         try (Throttler throttler = new Throttler(MAX_CONCURRENT_STREAMS)) {
969             String requestJson = jsonParser.toJson(resource);
970             ByteBuffer requestBytes = ByteBuffer.wrap(requestJson.getBytes(StandardCharsets.UTF_8));
971             String url = getUrl(new ResourceReference().setId(resource.getId()).setType(resource.getType()));
972             HeadersFrame headers = prepareHeaders(url, MediaType.APPLICATION_JSON, "PUT", requestBytes.capacity(),
973                     MediaType.APPLICATION_JSON);
974             LOGGER.trace("PUT {} HTTP/2 >> {}", url, requestJson);
975             Completable<@Nullable Stream> streamPromise = new Completable<>();
976             ContentStreamListenerAdapter contentStreamListener = new ContentStreamListenerAdapter();
977             session.newStream(headers, streamPromise, contentStreamListener);
978             // wait for stream to be opened
979             Stream stream = Objects.requireNonNull(streamPromise.get(TIMEOUT_SECONDS, TimeUnit.SECONDS));
980             stream.data(new DataFrame(stream.getId(), requestBytes, true), Callback.NOOP);
981             // wait for HTTP response
982             String contentJson = contentStreamListener.awaitResult();
983             String contentType = contentStreamListener.getContentType();
984             LOGGER.trace("HTTP/2 200 OK (Content-Type: {}) << {}", contentType, contentJson);
985             if (!MediaType.APPLICATION_JSON.equals(contentType)) {
986                 throw new ApiException("Unexpected Content-Type: " + contentType);
987             }
988             try {
989                 Resources resources = Objects.requireNonNull(jsonParser.fromJson(contentJson, Resources.class));
990                 if (LOGGER.isDebugEnabled()) {
991                     resources.getErrors().forEach(error -> LOGGER.debug("putResource() resources error:{}", error));
992                 }
993             } catch (JsonParseException e) {
994                 LOGGER.debug("putResource() parsing error json:{}", contentJson, e);
995                 throw new ApiException("Parsing error", e);
996             }
997         } catch (ExecutionException | TimeoutException e) {
998             throw new ApiException("putResource() error sending request", e);
999         }
1000     }
1001
1002     /**
1003      * Try to register the application key with the hub. Use the given application key if one is provided; otherwise the
1004      * hub will create a new one. Note: this requires an HTTP 1.1 client call.
1005      *
1006      * @param oldApplicationKey existing application key if any i.e. may be empty.
1007      * @return the existing or a newly created application key.
1008      * @throws HttpUnauthorizedException if the registration failed.
1009      * @throws ApiException if there was a communications error.
1010      * @throws InterruptedException
1011      */
1012     public String registerApplicationKey(@Nullable String oldApplicationKey)
1013             throws HttpUnauthorizedException, ApiException, InterruptedException {
1014         LOGGER.debug("registerApplicationKey()");
1015         String json = jsonParser.toJson((Objects.isNull(oldApplicationKey) || oldApplicationKey.isEmpty())
1016                 ? new CreateUserRequest(APPLICATION_ID)
1017                 : new CreateUserRequest(oldApplicationKey, APPLICATION_ID));
1018         Request httpRequest = httpClient.newRequest(registrationUrl).method(HttpMethod.POST)
1019                 .timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS)
1020                 .content(new StringContentProvider(json), MediaType.APPLICATION_JSON);
1021         ContentResponse contentResponse;
1022         try {
1023             LOGGER.trace("POST {} HTTP/1.1 >> {}", registrationUrl, json);
1024             contentResponse = httpRequest.send();
1025         } catch (TimeoutException | ExecutionException e) {
1026             throw new ApiException("HTTP processing error", e);
1027         }
1028         int httpStatus = contentResponse.getStatus();
1029         json = contentResponse.getContentAsString().trim();
1030         LOGGER.trace("HTTP/1.1 {} {} << {}", httpStatus, contentResponse.getReason(), json);
1031         if (httpStatus != HttpStatus.OK_200) {
1032             throw new ApiException("HTTP bad response");
1033         }
1034         try {
1035             List<SuccessResponse> entries = jsonParser.fromJson(json, SuccessResponse.GSON_TYPE);
1036             if (Objects.nonNull(entries) && !entries.isEmpty()) {
1037                 SuccessResponse response = entries.get(0);
1038                 Map<String, Object> responseSuccess = response.success;
1039                 if (Objects.nonNull(responseSuccess)) {
1040                     String newApplicationKey = (String) responseSuccess.get("username");
1041                     if (Objects.nonNull(newApplicationKey)) {
1042                         return newApplicationKey;
1043                     }
1044                 }
1045             }
1046         } catch (JsonParseException e) {
1047             LOGGER.debug("registerApplicationKey() parsing error json:{}", json, e);
1048         }
1049         throw new HttpUnauthorizedException("Application key registration failed");
1050     }
1051
1052     /**
1053      * Test the Hue Bridge connection state by attempting to connect and trying to execute a basic command that requires
1054      * authentication.
1055      *
1056      * @throws HttpUnauthorizedException if it was possible to connect but not to authenticate.
1057      * @throws ApiException if it was not possible to connect.
1058      * @throws InterruptedException
1059      */
1060     public void testConnectionState() throws HttpUnauthorizedException, ApiException, InterruptedException {
1061         LOGGER.debug("testConnectionState()");
1062         try {
1063             openPassive();
1064             getResourcesImpl(BRIDGE);
1065         } catch (ApiException e) {
1066             close2();
1067             throw e;
1068         }
1069     }
1070 }