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.nanoleaf.internal.handler;
15 import static org.openhab.binding.nanoleaf.internal.NanoleafBindingConstants.*;
17 import java.io.IOException;
19 import java.nio.charset.StandardCharsets;
20 import java.util.ArrayList;
21 import java.util.Arrays;
22 import java.util.Collection;
23 import java.util.List;
25 import java.util.Objects;
26 import java.util.Scanner;
27 import java.util.concurrent.CopyOnWriteArrayList;
28 import java.util.concurrent.ExecutionException;
29 import java.util.concurrent.ScheduledFuture;
30 import java.util.concurrent.TimeUnit;
31 import java.util.concurrent.TimeoutException;
33 import org.eclipse.jdt.annotation.NonNullByDefault;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.eclipse.jetty.client.HttpClient;
36 import org.eclipse.jetty.client.api.ContentResponse;
37 import org.eclipse.jetty.client.api.Request;
38 import org.eclipse.jetty.client.util.StringContentProvider;
39 import org.eclipse.jetty.http.HttpMethod;
40 import org.eclipse.jetty.http.HttpStatus;
41 import org.openhab.binding.nanoleaf.internal.NanoleafBadRequestException;
42 import org.openhab.binding.nanoleaf.internal.NanoleafBindingConstants;
43 import org.openhab.binding.nanoleaf.internal.NanoleafControllerListener;
44 import org.openhab.binding.nanoleaf.internal.NanoleafException;
45 import org.openhab.binding.nanoleaf.internal.NanoleafNotFoundException;
46 import org.openhab.binding.nanoleaf.internal.NanoleafUnauthorizedException;
47 import org.openhab.binding.nanoleaf.internal.OpenAPIUtils;
48 import org.openhab.binding.nanoleaf.internal.colors.NanoleafControllerColorChangeListener;
49 import org.openhab.binding.nanoleaf.internal.colors.NanoleafPanelColors;
50 import org.openhab.binding.nanoleaf.internal.commanddescription.NanoleafCommandDescriptionProvider;
51 import org.openhab.binding.nanoleaf.internal.config.NanoleafControllerConfig;
52 import org.openhab.binding.nanoleaf.internal.discovery.NanoleafPanelsDiscoveryService;
53 import org.openhab.binding.nanoleaf.internal.layout.ConstantPanelState;
54 import org.openhab.binding.nanoleaf.internal.layout.LayoutSettings;
55 import org.openhab.binding.nanoleaf.internal.layout.LivePanelState;
56 import org.openhab.binding.nanoleaf.internal.layout.NanoleafLayout;
57 import org.openhab.binding.nanoleaf.internal.layout.PanelState;
58 import org.openhab.binding.nanoleaf.internal.model.AuthToken;
59 import org.openhab.binding.nanoleaf.internal.model.BooleanState;
60 import org.openhab.binding.nanoleaf.internal.model.Brightness;
61 import org.openhab.binding.nanoleaf.internal.model.ControllerInfo;
62 import org.openhab.binding.nanoleaf.internal.model.Ct;
63 import org.openhab.binding.nanoleaf.internal.model.Effects;
64 import org.openhab.binding.nanoleaf.internal.model.Hue;
65 import org.openhab.binding.nanoleaf.internal.model.IntegerState;
66 import org.openhab.binding.nanoleaf.internal.model.Layout;
67 import org.openhab.binding.nanoleaf.internal.model.On;
68 import org.openhab.binding.nanoleaf.internal.model.PanelLayout;
69 import org.openhab.binding.nanoleaf.internal.model.PositionDatum;
70 import org.openhab.binding.nanoleaf.internal.model.Rhythm;
71 import org.openhab.binding.nanoleaf.internal.model.Sat;
72 import org.openhab.binding.nanoleaf.internal.model.State;
73 import org.openhab.binding.nanoleaf.internal.model.TouchEvents;
74 import org.openhab.binding.nanoleaf.internal.model.Write;
75 import org.openhab.core.config.core.Configuration;
76 import org.openhab.core.io.net.http.HttpClientFactory;
77 import org.openhab.core.library.types.DecimalType;
78 import org.openhab.core.library.types.HSBType;
79 import org.openhab.core.library.types.IncreaseDecreaseType;
80 import org.openhab.core.library.types.OnOffType;
81 import org.openhab.core.library.types.PercentType;
82 import org.openhab.core.library.types.QuantityType;
83 import org.openhab.core.library.types.RawType;
84 import org.openhab.core.library.types.StringType;
85 import org.openhab.core.library.unit.Units;
86 import org.openhab.core.thing.Bridge;
87 import org.openhab.core.thing.ChannelUID;
88 import org.openhab.core.thing.Thing;
89 import org.openhab.core.thing.ThingStatus;
90 import org.openhab.core.thing.ThingStatusDetail;
91 import org.openhab.core.thing.binding.BaseBridgeHandler;
92 import org.openhab.core.thing.binding.ThingHandlerCallback;
93 import org.openhab.core.thing.binding.ThingHandlerService;
94 import org.openhab.core.thing.util.ThingWebClientUtil;
95 import org.openhab.core.types.Command;
96 import org.openhab.core.types.RefreshType;
97 import org.slf4j.Logger;
98 import org.slf4j.LoggerFactory;
100 import com.google.gson.Gson;
101 import com.google.gson.JsonSyntaxException;
104 * The {@link NanoleafControllerHandler} is responsible for handling commands to the controller which
105 * affect all panels connected to it (e.g. selected effect)
107 * @author Martin Raepple - Initial contribution
108 * @author Stefan Höhn - Canvas Touch Support
109 * @author Kai Kreuzer - refactoring, bug fixing and code clean up
112 public class NanoleafControllerHandler extends BaseBridgeHandler implements NanoleafControllerColorChangeListener {
114 // Pairing interval in seconds
115 private static final int PAIRING_INTERVAL = 10;
116 private static final int CONNECT_TIMEOUT = 10;
118 private final Logger logger = LoggerFactory.getLogger(NanoleafControllerHandler.class);
119 private final HttpClientFactory httpClientFactory;
120 private final HttpClient httpClient;
122 private @Nullable HttpClient httpClientSSETouchEvent;
123 private @Nullable Request sseTouchjobRequest;
124 private final List<NanoleafControllerListener> controllerListeners = new CopyOnWriteArrayList<NanoleafControllerListener>();
125 private PanelLayout previousPanelLayout = new PanelLayout();
126 private final NanoleafPanelColors panelColors = new NanoleafPanelColors();
127 private boolean updateVisualLayout = true;
128 private byte @Nullable [] layoutImage;
130 private @NonNullByDefault({}) ScheduledFuture<?> pairingJob;
131 private @NonNullByDefault({}) ScheduledFuture<?> updateJob;
132 private @NonNullByDefault({}) ScheduledFuture<?> touchJob;
133 private final Gson gson = new Gson();
135 private @Nullable String address;
137 private int refreshIntervall;
138 private @Nullable String authToken;
139 private @Nullable String deviceType;
140 private @NonNullByDefault({}) ControllerInfo controllerInfo;
142 private boolean touchJobRunning = false;
144 public NanoleafControllerHandler(Bridge bridge, HttpClientFactory httpClientFactory) {
146 this.httpClientFactory = httpClientFactory;
147 this.httpClient = httpClientFactory.getCommonHttpClient();
150 private void initializeTouchHttpClient() {
151 String httpClientName = ThingWebClientUtil.buildWebClientConsumerName(thing.getUID(), null);
154 httpClientSSETouchEvent = httpClientFactory.createHttpClient(httpClientName);
155 final HttpClient localHttpClientSSETouchEvent = this.httpClientSSETouchEvent;
156 if (localHttpClientSSETouchEvent != null) {
157 localHttpClientSSETouchEvent.setConnectTimeout(CONNECT_TIMEOUT * 1000L);
158 localHttpClientSSETouchEvent.start();
160 } catch (Exception e) {
162 "Long running HttpClient for Nanoleaf controller handler {} cannot be started. Creating Handler failed.",
164 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
167 logger.debug("Using long SSE httpClient={} for {}}", httpClientSSETouchEvent, httpClientName);
171 public void initialize() {
172 logger.debug("Initializing the controller (bridge)");
173 this.panelColors.registerChangeListener(this);
174 updateStatus(ThingStatus.UNKNOWN);
175 NanoleafControllerConfig config = getConfigAs(NanoleafControllerConfig.class);
176 setAddress(config.address);
177 setPort(config.port);
178 setRefreshIntervall(config.refreshInterval);
179 String authToken = (config.authToken != null) ? config.authToken : "";
180 setAuthToken(authToken);
181 Map<String, String> properties = getThing().getProperties();
182 String propertyModelId = properties.get(Thing.PROPERTY_MODEL_ID);
183 if (hasTouchSupport(propertyModelId)) {
184 config.deviceType = DEVICE_TYPE_TOUCHSUPPORT;
185 initializeTouchHttpClient();
187 config.deviceType = DEVICE_TYPE_LIGHTPANELS;
190 setDeviceType(config.deviceType);
191 String propertyFirmwareVersion = properties.get(Thing.PROPERTY_FIRMWARE_VERSION);
194 if (!config.address.isEmpty() && !String.valueOf(config.port).isEmpty()) {
195 if (propertyFirmwareVersion != null && !propertyFirmwareVersion.isEmpty() && !OpenAPIUtils
196 .checkRequiredFirmware(properties.get(Thing.PROPERTY_MODEL_ID), propertyFirmwareVersion)) {
197 logger.warn("Nanoleaf controller firmware is too old: {}. Must be equal or higher than {}",
198 propertyFirmwareVersion, API_MIN_FW_VER_LIGHTPANELS);
199 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
200 "@text/error.nanoleaf.controller.incompatibleFirmware");
202 } else if (authToken != null && !authToken.isEmpty()) {
207 logger.debug("No token found. Start pairing background job");
208 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
209 "@text/error.nanoleaf.controller.noToken");
214 logger.warn("No IP address and port configured for the Nanoleaf controller");
215 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
216 "@text/error.nanoleaf.controller.noIp");
219 } catch (IllegalArgumentException iae) {
220 logger.warn("Nanoleaf controller firmware version not in format x.y.z: {}",
221 getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION));
222 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
223 "@text/error.nanoleaf.controller.incompatibleFirmware");
228 public void handleCommand(ChannelUID channelUID, Command command) {
229 logger.debug("Received command {} for channel {}", command, channelUID);
230 if (!ThingStatus.ONLINE.equals(getThing().getStatusInfo().getStatus())) {
231 logger.debug("Cannot handle command. Bridge is not online.");
234 if (command instanceof RefreshType) {
235 updateFromControllerInfo();
237 switch (channelUID.getId()) {
239 case CHANNEL_COLOR_TEMPERATURE:
240 case CHANNEL_COLOR_TEMPERATURE_ABS:
241 sendStateCommand(channelUID.getId(), command);
244 sendEffectCommand(command);
246 case CHANNEL_RHYTHM_MODE:
247 sendRhythmCommand(command);
250 logger.warn("Channel with id {} not handled", channelUID.getId());
254 } catch (NanoleafUnauthorizedException nue) {
255 logger.debug("Authorization for command {} to channelUID {} failed: {}", command, channelUID,
257 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
258 "@text/error.nanoleaf.controller.invalidToken");
259 } catch (NanoleafException ne) {
260 logger.debug("Handling command {} to channelUID {} failed: {}", command, channelUID, ne.getMessage());
261 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
262 "@text/error.nanoleaf.controller.communication");
268 public void handleRemoval() {
269 scheduler.execute(() -> {
271 Request deleteTokenRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(),
272 API_DELETE_USER, HttpMethod.DELETE);
273 ContentResponse deleteTokenResponse = OpenAPIUtils.sendOpenAPIRequest(deleteTokenRequest);
274 if (deleteTokenResponse.getStatus() != HttpStatus.NO_CONTENT_204) {
275 logger.warn("Failed to delete token for openHAB. Response code is {}",
276 deleteTokenResponse.getStatus());
279 logger.debug("Successfully deleted token for openHAB from controller");
280 } catch (NanoleafUnauthorizedException e) {
281 logger.warn("Attempt to delete token for openHAB failed. Token unauthorized.");
282 } catch (NanoleafException ne) {
283 logger.warn("Attempt to delete token for openHAB failed : {}", ne.getMessage());
286 super.handleRemoval();
287 logger.debug("Nanoleaf controller removed");
292 public void dispose() {
294 HttpClient localHttpClientSSETouchEvent = this.httpClientSSETouchEvent;
295 if (localHttpClientSSETouchEvent != null) {
297 localHttpClientSSETouchEvent.stop();
298 } catch (Exception e) {
300 this.httpClientSSETouchEvent = null;
303 logger.debug("Disposing handler for Nanoleaf controller {}", getThing().getUID());
307 public Collection<Class<? extends ThingHandlerService>> getServices() {
308 return List.of(NanoleafPanelsDiscoveryService.class, NanoleafCommandDescriptionProvider.class);
311 public boolean registerControllerListener(NanoleafControllerListener controllerListener) {
312 logger.debug("Register new listener for controller {}", getThing().getUID());
313 return controllerListeners.add(controllerListener);
316 public boolean unregisterControllerListener(NanoleafControllerListener controllerListener) {
317 logger.debug("Unregister listener for controller {}", getThing().getUID());
318 return controllerListeners.remove(controllerListener);
321 public NanoleafControllerConfig getControllerConfig() {
322 NanoleafControllerConfig config = new NanoleafControllerConfig();
323 config.address = Objects.requireNonNullElse(getAddress(), "");
324 config.port = getPort();
325 config.refreshInterval = getRefreshInterval();
326 config.authToken = getAuthToken();
327 config.deviceType = Objects.requireNonNullElse(getDeviceType(), "");
331 public String getLayout() {
332 String layoutView = "";
333 if (controllerInfo != null) {
334 PanelLayout panelLayout = controllerInfo.getPanelLayout();
335 Layout layout = panelLayout.getLayout();
336 layoutView = layout != null ? layout.getLayoutView() : "";
342 public synchronized void startPairingJob() {
343 if (pairingJob == null || pairingJob.isCancelled()) {
344 logger.debug("Start pairing job, interval={} sec", PAIRING_INTERVAL);
345 pairingJob = scheduler.scheduleWithFixedDelay(this::runPairing, 0L, PAIRING_INTERVAL, TimeUnit.SECONDS);
349 private synchronized void stopPairingJob() {
350 logger.debug("Stop pairing job {}", pairingJob != null ? pairingJob.isCancelled() : "pairing job = null");
351 if (pairingJob != null && !pairingJob.isCancelled()) {
352 pairingJob.cancel(true);
354 logger.debug("Stopped pairing job");
358 private synchronized void startUpdateJob() {
359 final String localAuthToken = getAuthToken();
360 if (localAuthToken != null && !localAuthToken.isEmpty()) {
361 if (updateJob == null || updateJob.isCancelled()) {
362 logger.debug("Start controller status job, repeat every {} sec", getRefreshInterval());
363 updateJob = scheduler.scheduleWithFixedDelay(this::runUpdate, 0L, getRefreshInterval(),
367 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
368 "@text/error.nanoleaf.controller.noToken");
372 private synchronized void stopUpdateJob() {
373 logger.debug("Stop update job {}", updateJob != null ? updateJob.isCancelled() : "update job = null");
374 if (updateJob != null && !updateJob.isCancelled()) {
375 updateJob.cancel(true);
377 logger.debug("Stopped status job");
381 private synchronized void startTouchJob() {
382 NanoleafControllerConfig config = getConfigAs(NanoleafControllerConfig.class);
383 if (!config.deviceType.equals(DEVICE_TYPE_TOUCHSUPPORT)) {
385 "NOT starting TouchJob for Controller {} because it has wrong device type '{}' vs required '{}'",
386 this.getThing().getUID(), config.deviceType, DEVICE_TYPE_TOUCHSUPPORT);
388 logger.debug("Starting TouchJob for Controller {}", getThing().getUID());
389 final String localAuthToken = getAuthToken();
390 if (localAuthToken != null && !localAuthToken.isEmpty()) {
391 if (touchJob != null && !touchJob.isDone()) {
392 logger.trace("tj: tj={} already running touchJobRunning = {} cancelled={} done={}", touchJob,
393 touchJobRunning, touchJob == null ? null : touchJob.isCancelled(),
394 touchJob == null ? null : touchJob.isDone());
396 logger.debug("tj: Starting NEW touch job : tj={} touchJobRunning={} cancelled={} done={}",
397 touchJob, touchJobRunning, touchJob == null ? null : touchJob.isCancelled(),
398 touchJob == null ? null : touchJob.isDone());
399 touchJob = scheduler.scheduleWithFixedDelay(this::runTouchDetection, 0L, 1L, TimeUnit.SECONDS);
402 logger.error("starting TouchJob for Controller {} failed - missing token", getThing().getUID());
408 private synchronized void stopTouchJob() {
409 logger.debug("Stop touch job {}", touchJob != null ? touchJob.isCancelled() : "touchJob job = null");
410 if (touchJob != null) {
411 logger.trace("tj: touch job stopping for {} with client {}", thing.getUID(), httpClientSSETouchEvent);
413 final Request localSSERequest = sseTouchjobRequest;
414 if (localSSERequest != null) {
415 localSSERequest.abort(new NanoleafException("Touch detection stopped"));
417 if (!touchJob.isCancelled()) {
418 touchJob.cancel(true);
422 touchJobRunning = false;
423 logger.debug("tj: touch job stopped for {} with client {}", thing.getUID(), httpClientSSETouchEvent);
427 private boolean hasTouchSupport(@Nullable String deviceType) {
428 return NanoleafBindingConstants.MODELS_WITH_TOUCHSUPPORT.contains(deviceType);
431 private void runUpdate() {
432 logger.debug("Run update job");
435 updateFromControllerInfo();
437 updateStatus(ThingStatus.ONLINE);
438 } catch (NanoleafUnauthorizedException nae) {
439 logger.debug("Status update unauthorized for controller {}: {}", getThing().getUID(), nae.getMessage());
440 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
441 "@text/error.nanoleaf.controller.invalidToken");
442 final String localAuthToken = getAuthToken();
443 if (localAuthToken == null || localAuthToken.isEmpty()) {
444 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
445 "@text/error.nanoleaf.controller.noToken");
447 } catch (NanoleafException ne) {
448 logger.debug("Status update failed for controller {} : {}", getThing().getUID(), ne.getMessage());
449 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
450 "@text/error.nanoleaf.controller.communication");
451 } catch (RuntimeException e) {
452 logger.debug("Update job failed", e);
453 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/error.nanoleaf.controller.runtime");
457 private void runPairing() {
458 logger.debug("Run pairing job");
461 final String localAuthToken = getAuthToken();
462 if (localAuthToken != null && !localAuthToken.isEmpty()) {
463 if (pairingJob != null) {
464 pairingJob.cancel(false);
467 logger.debug("Authentication token found. Canceling pairing job");
471 ContentResponse authTokenResponse = OpenAPIUtils
472 .requestBuilder(httpClient, getControllerConfig(), API_ADD_USER, HttpMethod.POST)
473 .timeout(20L, TimeUnit.SECONDS).send();
474 String authTokenResponseString = (authTokenResponse != null) ? authTokenResponse.getContentAsString() : "";
475 if (logger.isTraceEnabled()) {
476 logger.trace("Auth token response: {}", authTokenResponseString);
479 if (authTokenResponse != null && authTokenResponse.getStatus() != HttpStatus.OK_200) {
480 logger.debug("Pairing pending for {}. Controller returns status code {}", getThing().getUID(),
481 authTokenResponse.getStatus());
483 AuthToken authTokenObject = gson.fromJson(authTokenResponseString, AuthToken.class);
484 authTokenObject = (authTokenObject != null) ? authTokenObject : new AuthToken();
485 if (authTokenObject.getAuthToken().isEmpty()) {
486 logger.debug("No auth token found in response: {}", authTokenResponseString);
487 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
488 "@text/error.nanoleaf.controller.pairingFailed");
489 throw new NanoleafException(authTokenResponseString);
492 logger.debug("Pairing succeeded.");
493 Configuration config = editConfiguration();
495 config.put(NanoleafControllerConfig.AUTH_TOKEN, authTokenObject.getAuthToken());
496 updateConfiguration(config);
497 updateStatus(ThingStatus.ONLINE);
498 // Update local field
499 setAuthToken(authTokenObject.getAuthToken());
505 } catch (JsonSyntaxException e) {
506 logger.warn("Received invalid data", e);
507 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
508 "@text/error.nanoleaf.controller.invalidData");
509 } catch (NanoleafException ne) {
510 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
511 "@text/error.nanoleaf.controller.noTokenReceived");
512 } catch (ExecutionException | TimeoutException | InterruptedException e) {
513 logger.debug("Cannot send authorization request to controller: ", e);
514 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
515 "@text/error.nanoleaf.controller.authRequest");
516 } catch (RuntimeException e) {
517 logger.warn("Pairing job failed", e);
518 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/error.nanoleaf.controller.runtime");
519 } catch (Exception e) {
520 logger.warn("Cannot start http client", e);
521 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
522 "@text/error.nanoleaf.controller.noClient");
526 private synchronized void runTouchDetection() {
527 final HttpClient localhttpSSEClientTouchEvent = httpClientSSETouchEvent;
528 int eventHashcode = -1;
529 if (localhttpSSEClientTouchEvent != null) {
530 eventHashcode = localhttpSSEClientTouchEvent.hashCode();
532 if (touchJobRunning) {
533 logger.trace("tj: touch job {} touch job already running. quitting. {} controller {} with {}\",\n",
534 touchJob, eventHashcode, thing.getUID(), httpClientSSETouchEvent);
537 URI eventUri = OpenAPIUtils.getUri(getControllerConfig(), API_EVENTS, "id=4");
538 logger.debug("tj: touch job request registering for {} with client {}", thing.getUID(),
539 httpClientSSETouchEvent);
540 touchJobRunning = true;
541 if (localhttpSSEClientTouchEvent != null) {
542 localhttpSSEClientTouchEvent.setIdleTimeout(CONNECT_TIMEOUT * 1000L);
543 sseTouchjobRequest = localhttpSSEClientTouchEvent.newRequest(eventUri);
544 final Request localSSETouchjobRequest = sseTouchjobRequest;
545 if (localSSETouchjobRequest != null) {
546 int requestHashCode = localSSETouchjobRequest.hashCode();
548 logger.debug("tj: triggering new touch job request {} for {} with client {}", requestHashCode,
549 thing.getUID(), eventHashcode);
550 localSSETouchjobRequest.onResponseContent((response, content) -> {
551 String s = StandardCharsets.UTF_8.decode(content).toString();
552 logger.debug("touch detected for controller {}", thing.getUID());
553 logger.trace("content {}", s);
554 try (Scanner eventContent = new Scanner(s)) {
555 while (eventContent.hasNextLine()) {
556 String line = eventContent.nextLine().trim();
557 if (line.startsWith("data:")) {
558 String json = line.substring(5).trim();
561 TouchEvents touchEvents = gson.fromJson(json, TouchEvents.class);
562 handleTouchEvents(Objects.requireNonNull(touchEvents));
563 } catch (JsonSyntaxException e) {
564 logger.error("Couldn't parse touch event json {}", json);
569 logger.debug("leaving touch onContent");
570 }).onResponseSuccess((response) -> {
571 logger.trace("tj: r={} touch event SUCCESS: {}", response.getRequest(), response);
572 }).onResponseFailure((response, failure) -> {
573 logger.trace("tj: r={} touch event FAILURE. Touchjob not running anymore for controller {}",
574 response.getRequest(), thing.getUID());
575 }).send((result) -> {
577 "tj: r={} touch event COMPLETE. Touchjob not running anymore for controller {} failed: {} succeeded: {}",
578 result.getRequest(), thing.getUID(), result.isFailed(), result.isSucceeded());
579 touchJobRunning = false;
583 logger.trace("tj: started touch job request for {} with {} at {}", thing.getUID(),
584 httpClientSSETouchEvent, eventUri);
585 } catch (NanoleafException | RuntimeException e) {
586 logger.warn("tj: setting up TouchDetection failed for controller {} with {}\",\n", thing.getUID(),
587 httpClientSSETouchEvent);
588 logger.warn("tj: setting up TouchDetection failed with exception", e);
590 logger.trace("tj: touch job {} started for new request {} controller {} with {}\",\n",
591 touchJob.hashCode(), eventHashcode, thing.getUID(), httpClientSSETouchEvent);
597 private void handleTouchEvents(TouchEvents touchEvents) {
598 touchEvents.getEvents().forEach((event) -> {
599 logger.debug("panel: {} gesture id: {}", event.getPanelId(), event.getGesture());
600 // Swipes go to the controller, taps go to the individual panel
601 if (event.getPanelId().equals(CONTROLLER_PANEL_ID)) {
602 logger.debug("Triggering controller {} with gesture {}.", thing.getUID(), event.getGesture());
603 updateControllerGesture(event.getGesture());
605 getThing().getThings().forEach((child) -> {
606 NanoleafPanelHandler panelHandler = (NanoleafPanelHandler) child.getHandler();
607 if (panelHandler != null) {
608 logger.trace("Checking available panel -{}- versus event panel -{}-", panelHandler.getPanelID(),
610 if (panelHandler.getPanelID().equals(Integer.valueOf(event.getPanelId()))) {
611 logger.debug("Panel {} found. Triggering item with gesture {}.", panelHandler.getPanelID(),
613 panelHandler.updatePanelGesture(event.getGesture());
623 * Apply the swipe gesture to the controller
625 * @param gesture Only swipes are supported on the complete nanoleaf panels
627 private void updateControllerGesture(int gesture) {
630 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_UP);
633 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_DOWN);
636 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_LEFT);
639 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_RIGHT);
644 private void updateFromControllerInfo() throws NanoleafException {
645 logger.debug("Update channels for controller {}", thing.getUID());
646 controllerInfo = receiveControllerInfo();
647 State state = controllerInfo.getState();
649 OnOffType powerState = state.getOnOff();
651 Ct colorTemperature = state.getColorTemperature();
653 float colorTempPercent = 0.0F;
656 if (colorTemperature != null) {
657 updateState(CHANNEL_COLOR_TEMPERATURE_ABS, new QuantityType(colorTemperature.getValue(), Units.KELVIN));
658 Integer min = colorTemperature.getMin();
659 hue = min == null ? 0 : min;
660 Integer max = colorTemperature.getMax();
661 saturation = max == null ? 0 : max;
662 colorTempPercent = (colorTemperature.getValue() - hue) / (saturation - hue)
663 * PercentType.HUNDRED.intValue();
666 updateState(CHANNEL_COLOR_TEMPERATURE, new PercentType(Float.toString(colorTempPercent)));
667 updateState(CHANNEL_EFFECT, new StringType(controllerInfo.getEffects().getSelect()));
668 Hue stateHue = state.getHue();
669 hue = stateHue != null ? stateHue.getValue() : 0;
671 Sat stateSaturation = state.getSaturation();
672 saturation = stateSaturation != null ? stateSaturation.getValue() : 0;
674 Brightness stateBrightness = state.getBrightness();
675 int brightness = stateBrightness != null ? stateBrightness.getValue() : 0;
676 HSBType stateColor = new HSBType(new DecimalType(hue), new PercentType(saturation),
677 new PercentType(powerState == OnOffType.ON ? brightness : 0));
679 updateState(CHANNEL_COLOR, stateColor);
680 updateState(CHANNEL_COLOR_MODE, new StringType(state.getColorMode()));
681 updateState(CHANNEL_RHYTHM_ACTIVE, OnOffType.from(controllerInfo.getRhythm().getRhythmActive()));
682 updateState(CHANNEL_RHYTHM_MODE, new DecimalType(controllerInfo.getRhythm().getRhythmMode()));
683 updateState(CHANNEL_RHYTHM_STATE, OnOffType.from(controllerInfo.getRhythm().getRhythmConnected()));
686 if (EFFECT_NAME_SOLID_COLOR.equals(controllerInfo.getEffects().getSelect())) {
687 setSolidColor(stateColor);
690 updateConfiguration();
691 updateLayout(controllerInfo.getPanelLayout());
692 updateVisualState(controllerInfo.getPanelLayout(), powerState);
694 for (NanoleafControllerListener controllerListener : controllerListeners) {
695 controllerListener.onControllerInfoFetched(getThing().getUID(), controllerInfo);
699 private void setSolidColor(HSBType color) {
700 // If the panels are set to solid color, they are read from the state
701 PanelLayout panelLayout = controllerInfo.getPanelLayout();
702 Layout layout = panelLayout.getLayout();
704 if (layout != null) {
705 List<PositionDatum> positionData = layout.getPositionData();
706 if (positionData != null) {
707 List<Integer> allPanelIds = new ArrayList<>(positionData.size());
708 for (PositionDatum pd : positionData) {
709 allPanelIds.add(pd.getPanelId());
712 panelColors.setMultiple(allPanelIds, color);
714 logger.debug("Missing position datum when setting solid color for {}", getThing().getUID());
717 logger.debug("Missing layout when setting solid color for {}", getThing().getUID());
721 private void updateConfiguration() {
722 // only update the Thing config if value isn't set yet
723 if (getConfig().get(NanoleafControllerConfig.DEVICE_TYPE) == null) {
724 Configuration config = editConfiguration();
725 if (hasTouchSupport(controllerInfo.getModel())) {
726 config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_TOUCHSUPPORT);
727 logger.debug("Set to device type {}", DEVICE_TYPE_TOUCHSUPPORT);
729 config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_LIGHTPANELS);
730 logger.debug("Set to device type {}", DEVICE_TYPE_LIGHTPANELS);
732 updateConfiguration(config);
733 if (logger.isTraceEnabled()) {
734 getConfig().getProperties().forEach((key, value) -> {
735 logger.trace("Configuration property: key {} value {}", key, value);
741 private void updateProperties() {
742 // update bridge properties which may have changed, or are not present during discovery
743 Map<String, String> properties = editProperties();
744 properties.put(Thing.PROPERTY_SERIAL_NUMBER, controllerInfo.getSerialNo());
745 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, controllerInfo.getFirmwareVersion());
746 properties.put(Thing.PROPERTY_MODEL_ID, controllerInfo.getModel());
747 properties.put(Thing.PROPERTY_VENDOR, controllerInfo.getManufacturer());
748 updateProperties(properties);
749 if (logger.isTraceEnabled()) {
750 getThing().getProperties().forEach((key, value) -> {
751 logger.trace("Thing property: key {} value {}", key, value);
756 private void updateVisualState(PanelLayout panelLayout, OnOffType powerState) {
757 ChannelUID stateChannel = new ChannelUID(getThing().getUID(), CHANNEL_VISUAL_STATE);
760 PanelState panelState;
761 if (OnOffType.OFF.equals(powerState)) {
762 // If powered off: show all panels as black
763 panelState = new ConstantPanelState(HSBType.BLACK);
765 // Static color for panels, use it
766 panelState = new LivePanelState(panelColors);
769 LayoutSettings settings = new LayoutSettings(false, true, true, true);
770 byte[] bytes = NanoleafLayout.render(panelLayout, panelState, settings);
771 if (bytes.length > 0) {
772 updateState(stateChannel, new RawType(bytes, "image/png"));
773 logger.trace("Rendered visual state of panel {} in updateState has {} bytes", getThing().getUID(),
776 logger.debug("Visual state of {} failed to produce any image", getThing().getUID());
778 } catch (IOException ioex) {
779 logger.warn("Failed to create state image", ioex);
783 private void updateLayout(PanelLayout panelLayout) {
784 ChannelUID layoutChannel = new ChannelUID(getThing().getUID(), CHANNEL_LAYOUT);
785 ThingHandlerCallback callback = getCallback();
786 if (callback != null) {
787 if (!callback.isChannelLinked(layoutChannel)) {
788 // Don't generate image unless it is used
793 if (layoutImage != null && previousPanelLayout.equals(panelLayout)) {
794 logger.trace("Not rendering panel layout for {} as it is the same as previous rendered panel layout",
795 getThing().getUID());
800 LayoutSettings settings = new LayoutSettings(true, false, true, false);
801 byte[] bytes = NanoleafLayout.render(panelLayout, new LivePanelState(panelColors), settings);
802 if (bytes.length > 0) {
803 updateState(layoutChannel, new RawType(bytes, "image/png"));
805 previousPanelLayout = panelLayout;
806 logger.trace("Rendered layout of panel {} in updateState has {} bytes", getThing().getUID(),
809 logger.debug("Layout of {} failed to produce any image", getThing().getUID());
812 } catch (IOException ioex) {
813 logger.warn("Failed to create layout image", ioex);
817 private ControllerInfo receiveControllerInfo() throws NanoleafException, NanoleafUnauthorizedException {
818 ContentResponse controllerlInfoJSON = OpenAPIUtils.sendOpenAPIRequest(OpenAPIUtils.requestBuilder(httpClient,
819 getControllerConfig(), API_GET_CONTROLLER_INFO, HttpMethod.GET));
820 ControllerInfo controllerInfo = gson.fromJson(controllerlInfoJSON.getContentAsString(), ControllerInfo.class);
821 return Objects.requireNonNull(controllerInfo);
824 private void sendStateCommand(String channel, Command command) throws NanoleafException {
825 State stateObject = new State();
828 if (command instanceof OnOffType) {
829 // On/Off command - turns controller on/off
830 BooleanState state = new On();
831 state.setValue(OnOffType.ON.equals(command));
832 stateObject.setState(state);
833 } else if (command instanceof HSBType) {
834 // regular color HSB command
835 IntegerState h = new Hue();
836 IntegerState s = new Sat();
837 IntegerState b = new Brightness();
838 h.setValue(((HSBType) command).getHue().intValue());
839 s.setValue(((HSBType) command).getSaturation().intValue());
840 b.setValue(((HSBType) command).getBrightness().intValue());
841 setSolidColor((HSBType) command);
842 stateObject.setState(h);
843 stateObject.setState(s);
844 stateObject.setState(b);
845 } else if (command instanceof PercentType) {
846 // brightness command
847 IntegerState b = new Brightness();
848 b.setValue(((PercentType) command).intValue());
849 stateObject.setState(b);
850 } else if (command instanceof IncreaseDecreaseType) {
851 // increase/decrease brightness
852 if (controllerInfo != null) {
854 Brightness brightness = controllerInfo.getState().getBrightness();
857 if (brightness != null) {
859 Integer min = brightness.getMin();
860 brightnessMin = (min == null) ? 0 : min;
862 Integer max = brightness.getMax();
863 brightnessMax = (max == null) ? 0 : max;
865 if (IncreaseDecreaseType.INCREASE.equals(command)) {
867 Math.min(brightnessMax, brightness.getValue() + BRIGHTNESS_STEP_SIZE));
870 Math.max(brightnessMin, brightness.getValue() - BRIGHTNESS_STEP_SIZE));
872 stateObject.setState(brightness);
873 logger.debug("Setting controller brightness to {}", brightness.getValue());
874 // update controller info in case new command is sent before next update job interval
875 controllerInfo.getState().setBrightness(brightness);
877 logger.debug("Couldn't set brightness as it was null!");
881 logger.warn("Unhandled command {} with command type: {}", command, command.getClass().getName());
885 case CHANNEL_COLOR_TEMPERATURE:
886 if (command instanceof PercentType) {
887 // Color temperature (percent)
888 IntegerState state = new Ct();
890 Ct colorTemperature = controllerInfo.getState().getColorTemperature();
894 if (colorTemperature != null) {
896 Integer min = colorTemperature.getMin();
897 colorMin = (min == null) ? 0 : min;
900 Integer max = colorTemperature.getMax();
901 colorMax = (max == null) ? 0 : max;
904 state.setValue(Math.round((colorMax - colorMin) * (100 - ((PercentType) command).intValue())
905 / PercentType.HUNDRED.floatValue() + colorMin));
906 stateObject.setState(state);
908 logger.warn("Unhandled command type: {}", command.getClass().getName());
912 case CHANNEL_COLOR_TEMPERATURE_ABS:
913 // Color temperature (absolute)
914 IntegerState state = new Ct();
915 if (command instanceof DecimalType) {
916 state.setValue(((DecimalType) command).intValue());
917 } else if (command instanceof QuantityType) {
918 QuantityType<?> tempKelvin = ((QuantityType) command).toInvertibleUnit(Units.KELVIN);
919 if (tempKelvin == null) {
920 logger.warn("Cannot convert color temperature {} to Kelvin.", command);
923 state.setValue(tempKelvin.intValue());
925 logger.warn("Unhandled command type: {}", command.getClass().getName());
929 stateObject.setState(state);
932 logger.warn("Unhandled command type: {}", command.getClass().getName());
936 Request setNewStateRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_SET_VALUE,
938 setNewStateRequest.content(new StringContentProvider(gson.toJson(stateObject)), "application/json");
939 OpenAPIUtils.sendOpenAPIRequest(setNewStateRequest);
942 private void sendEffectCommand(Command command) throws NanoleafException {
943 Effects effects = new Effects();
944 if (command instanceof StringType) {
945 effects.setSelect(command.toString());
946 Request setNewEffectRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_EFFECT,
948 String content = gson.toJson(effects);
949 logger.debug("sending effect command from controller {}: {}", getThing().getUID(), content);
950 setNewEffectRequest.content(new StringContentProvider(content), "application/json");
951 OpenAPIUtils.sendOpenAPIRequest(setNewEffectRequest);
953 logger.warn("Unhandled command type: {}", command.getClass().getName());
957 private void sendRhythmCommand(Command command) throws NanoleafException {
958 Rhythm rhythm = new Rhythm();
959 if (command instanceof DecimalType) {
960 rhythm.setRhythmMode(((DecimalType) command).intValue());
961 Request setNewRhythmRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(),
962 API_RHYTHM_MODE, HttpMethod.PUT);
963 setNewRhythmRequest.content(new StringContentProvider(gson.toJson(rhythm)), "application/json");
964 OpenAPIUtils.sendOpenAPIRequest(setNewRhythmRequest);
966 logger.warn("Unhandled command type: {}", command.getClass().getName());
970 private boolean hasStaticEffect() {
971 return EFFECT_NAME_STATIC_COLOR.equals(controllerInfo.getEffects().getSelect())
972 || EFFECT_NAME_SOLID_COLOR.equals(controllerInfo.getEffects().getSelect());
976 * Checks if we are in a mode where color changes should be rendered.
978 * @return True if a color change on a panel should be rendered
980 private boolean showsUpdatedColors() {
981 if (!hasStaticEffect()) {
982 logger.trace("Not updating colors as the device doesnt have a static/solid effect");
986 State state = controllerInfo.getState();
987 OnOffType powerState = state.getOnOff();
988 return OnOffType.ON.equals(powerState);
992 public void onPanelChangedColor() {
993 if (updateVisualLayout && showsUpdatedColors()) {
994 // Update the visual state if a panel has changed color
995 updateVisualState(controllerInfo.getPanelLayout(), controllerInfo.getState().getOnOff());
997 logger.trace("Not updating colors. Update visual layout: {}", updateVisualLayout);
1002 * For individual panels to get access to the panel colors.
1004 * @return Information about colors of panels.
1006 public NanoleafPanelColors getColorInformation() {
1010 private void updatePanelColors() {
1011 // get panel color data from controller
1013 Effects effects = new Effects();
1014 Write write = new Write();
1015 write.setCommand("request");
1016 write.setAnimName(EFFECT_NAME_STATIC_COLOR);
1017 effects.setWrite(write);
1019 NanoleafControllerConfig config = getControllerConfig();
1020 logger.debug("Sending Request from Panel for getColor()");
1021 Request setPanelUpdateRequest = OpenAPIUtils.requestBuilder(httpClient, config, API_EFFECT, HttpMethod.PUT);
1022 setPanelUpdateRequest.content(new StringContentProvider(gson.toJson(effects)), "application/json");
1023 ContentResponse panelData = OpenAPIUtils.sendOpenAPIRequest(setPanelUpdateRequest);
1025 parsePanelData(config, panelData);
1027 } catch (NanoleafNotFoundException nfe) {
1028 logger.debug("Panel data could not be retrieved as no data was returned (static type missing?) : {}",
1030 } catch (NanoleafBadRequestException nfe) {
1032 "Panel data could not be retrieved as request not expected(static type missing / dynamic type on) : {}",
1034 } catch (NanoleafException nue) {
1035 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
1036 "@text/error.nanoleaf.panel.communication");
1037 logger.debug("Panel data could not be retrieved: {}", nue.getMessage());
1041 void parsePanelData(NanoleafControllerConfig config, ContentResponse panelData) {
1042 // panelData is in format (numPanels, (PanelId, 1, R, G, B, W, TransitionTime) * numPanel)
1044 Write response = null;
1046 String panelDataContent = panelData.getContentAsString();
1048 response = gson.fromJson(panelDataContent, Write.class);
1049 } catch (JsonSyntaxException jse) {
1050 logger.warn("Unable to parse panel data information from Nanoleaf", jse);
1051 logger.trace("Panel Data which couldn't be parsed: {}", panelDataContent);
1054 if (response != null) {
1056 updateVisualLayout = false;
1057 String[] tokenizedData = response.getAnimData().split(" ");
1058 if (config.deviceType.equals(CONFIG_DEVICE_TYPE_LIGHTPANELS)
1059 || config.deviceType.equals(CONFIG_DEVICE_TYPE_CANVAS)) {
1060 // panelData is in format (numPanels (PanelId 1 R G B W TransitionTime) * numPanel)
1061 String[] panelDataPoints = Arrays.copyOfRange(tokenizedData, 1, tokenizedData.length);
1062 for (int i = 0; i < panelDataPoints.length; i++) {
1064 // found panel data - store it
1065 panelColors.setPanelColor(Integer.valueOf(panelDataPoints[i]),
1066 HSBType.fromRGB(Integer.parseInt(panelDataPoints[i + 2]),
1067 Integer.parseInt(panelDataPoints[i + 3]),
1068 Integer.parseInt(panelDataPoints[i + 4])));
1072 // panelData is in format (0 numPanels (quotient(panelID) remainder(panelID) R G B W 0
1073 // quotient(TransitionTime) remainder(TransitionTime)) * numPanel)
1074 String[] panelDataPoints = Arrays.copyOfRange(tokenizedData, 2, tokenizedData.length);
1075 for (int i = 0; i < panelDataPoints.length; i++) {
1077 Integer idQuotient = Integer.valueOf(panelDataPoints[i]);
1078 Integer idRemainder = Integer.valueOf(panelDataPoints[i + 1]);
1079 Integer idNum = idQuotient * 256 + idRemainder;
1080 // found panel data - store it
1081 panelColors.setPanelColor(idNum,
1082 HSBType.fromRGB(Integer.parseInt(panelDataPoints[i + 3]),
1083 Integer.parseInt(panelDataPoints[i + 4]),
1084 Integer.parseInt(panelDataPoints[i + 5])));
1089 updateVisualLayout = true;
1090 onPanelChangedColor();
1095 private @Nullable String getAddress() {
1099 private void setAddress(String address) {
1100 this.address = address;
1103 private int getPort() {
1107 private void setPort(int port) {
1111 private int getRefreshInterval() {
1112 return refreshIntervall;
1115 private void setRefreshIntervall(int refreshIntervall) {
1116 this.refreshIntervall = refreshIntervall;
1120 private String getAuthToken() {
1124 private void setAuthToken(@Nullable String authToken) {
1125 this.authToken = authToken;
1129 private String getDeviceType() {
1133 private void setDeviceType(String deviceType) {
1134 this.deviceType = deviceType;
1137 private void stopAllJobs() {