2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.nanoleaf.internal.handler;
15 import static org.openhab.binding.nanoleaf.internal.NanoleafBindingConstants.*;
18 import java.nio.ByteBuffer;
19 import java.nio.charset.StandardCharsets;
20 import java.util.List;
22 import java.util.Objects;
23 import java.util.Scanner;
24 import java.util.concurrent.CopyOnWriteArrayList;
25 import java.util.concurrent.ExecutionException;
26 import java.util.concurrent.ScheduledFuture;
27 import java.util.concurrent.TimeUnit;
28 import java.util.concurrent.TimeoutException;
30 import org.apache.commons.lang.StringUtils;
31 import org.eclipse.jdt.annotation.NonNullByDefault;
32 import org.eclipse.jdt.annotation.Nullable;
33 import org.eclipse.jetty.client.HttpClient;
34 import org.eclipse.jetty.client.api.ContentResponse;
35 import org.eclipse.jetty.client.api.Request;
36 import org.eclipse.jetty.client.api.Response;
37 import org.eclipse.jetty.client.api.Result;
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.*;
42 import org.openhab.binding.nanoleaf.internal.config.NanoleafControllerConfig;
43 import org.openhab.binding.nanoleaf.internal.model.*;
44 import org.openhab.core.config.core.Configuration;
45 import org.openhab.core.library.types.DecimalType;
46 import org.openhab.core.library.types.HSBType;
47 import org.openhab.core.library.types.IncreaseDecreaseType;
48 import org.openhab.core.library.types.OnOffType;
49 import org.openhab.core.library.types.PercentType;
50 import org.openhab.core.library.types.StringType;
51 import org.openhab.core.thing.Bridge;
52 import org.openhab.core.thing.ChannelUID;
53 import org.openhab.core.thing.Thing;
54 import org.openhab.core.thing.ThingStatus;
55 import org.openhab.core.thing.ThingStatusDetail;
56 import org.openhab.core.thing.binding.BaseBridgeHandler;
57 import org.openhab.core.types.Command;
58 import org.openhab.core.types.RefreshType;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 import com.google.gson.Gson;
63 import com.google.gson.JsonSyntaxException;
66 * The {@link NanoleafControllerHandler} is responsible for handling commands to the controller which
67 * affect all panels connected to it (e.g. selected effect)
69 * @author Martin Raepple - Initial contribution
70 * @author Stefan Höhn - Canvas Touch Support
73 public class NanoleafControllerHandler extends BaseBridgeHandler {
75 // Pairing interval in seconds
76 private static final int PAIRING_INTERVAL = 25;
78 // Panel discovery interval in seconds
79 private static final int PANEL_DISCOVERY_INTERVAL = 30;
81 private final Logger logger = LoggerFactory.getLogger(NanoleafControllerHandler.class);
82 private HttpClient httpClient;
83 private List<NanoleafControllerListener> controllerListeners = new CopyOnWriteArrayList<>();
85 // Pairing, update and panel discovery jobs and touch event job
86 private @NonNullByDefault({}) ScheduledFuture<?> pairingJob;
87 private @NonNullByDefault({}) ScheduledFuture<?> updateJob;
88 private @NonNullByDefault({}) ScheduledFuture<?> panelDiscoveryJob;
89 private @NonNullByDefault({}) ScheduledFuture<?> touchJob;
91 // JSON parser for API responses
92 private final Gson gson = new Gson();
94 // Controller configuration settings and channel values
95 private @Nullable String address;
97 private int refreshIntervall;
98 private @Nullable String authToken;
99 private @Nullable String deviceType;
100 private @NonNullByDefault({}) ControllerInfo controllerInfo;
102 public NanoleafControllerHandler(Bridge bridge, HttpClient httpClient) {
104 this.httpClient = httpClient;
108 public void initialize() {
109 logger.debug("Initializing the controller (bridge)");
110 updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.BRIDGE_UNINITIALIZED);
111 NanoleafControllerConfig config = getConfigAs(NanoleafControllerConfig.class);
112 setAddress(config.address);
113 setPort(config.port);
114 setRefreshIntervall(config.refreshInterval);
115 setAuthToken(config.authToken);
118 String property = getThing().getProperties().get(Thing.PROPERTY_MODEL_ID);
119 if (MODEL_ID_CANVAS.equals(property)) {
120 config.deviceType = DEVICE_TYPE_CANVAS;
122 config.deviceType = DEVICE_TYPE_LIGHTPANELS;
124 setDeviceType(config.deviceType);
127 Map<String, String> properties = getThing().getProperties();
128 if (StringUtils.isEmpty(getAddress()) || StringUtils.isEmpty(String.valueOf(getPort()))) {
129 logger.warn("No IP address and port configured for the Nanoleaf controller");
130 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
131 "@text/error.nanoleaf.controller.noIp");
133 } else if (!StringUtils.isEmpty(properties.get(Thing.PROPERTY_FIRMWARE_VERSION))
134 && !OpenAPIUtils.checkRequiredFirmware(properties.get(Thing.PROPERTY_MODEL_ID),
135 properties.get(Thing.PROPERTY_FIRMWARE_VERSION))) {
136 logger.warn("Nanoleaf controller firmware is too old: {}. Must be equal or higher than {}",
137 properties.get(Thing.PROPERTY_FIRMWARE_VERSION), API_MIN_FW_VER_LIGHTPANELS);
138 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
139 "@text/error.nanoleaf.controller.incompatibleFirmware");
141 } else if (StringUtils.isEmpty(getAuthToken())) {
142 logger.debug("No token found. Start pairing background job");
143 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
144 "@text/error.nanoleaf.controller.noToken");
147 stopPanelDiscoveryJob();
149 logger.debug("Controller is online. Stop pairing job, start update & panel discovery jobs");
150 updateStatus(ThingStatus.ONLINE);
153 startPanelDiscoveryJob();
156 } catch (IllegalArgumentException iae) {
157 logger.warn("Nanoleaf controller firmware version not in format x.y.z: {}",
158 getThing().getProperties().get(Thing.PROPERTY_FIRMWARE_VERSION));
159 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
160 "@text/error.nanoleaf.controller.incompatibleFirmware");
165 public void handleCommand(ChannelUID channelUID, Command command) {
166 logger.debug("Received command {} for channel {}", command, channelUID);
167 if (!ThingStatus.ONLINE.equals(getThing().getStatusInfo().getStatus())) {
168 logger.debug("Cannot handle command. Bridge is not online.");
172 if (command instanceof RefreshType) {
173 updateFromControllerInfo();
175 switch (channelUID.getId()) {
178 case CHANNEL_COLOR_TEMPERATURE:
179 case CHANNEL_COLOR_TEMPERATURE_ABS:
180 case CHANNEL_PANEL_LAYOUT:
181 sendStateCommand(channelUID.getId(), command);
184 sendEffectCommand(command);
186 case CHANNEL_RHYTHM_MODE:
187 sendRhythmCommand(command);
190 logger.warn("Channel with id {} not handled", channelUID.getId());
194 } catch (NanoleafUnauthorizedException nae) {
195 logger.warn("Authorization for command {} to channelUID {} failed: {}", command, channelUID,
197 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
198 "@text/error.nanoleaf.controller.invalidToken");
199 } catch (NanoleafException ne) {
200 logger.warn("Handling command {} to channelUID {} failed: {}", command, channelUID, ne.getMessage());
201 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
202 "@text/error.nanoleaf.controller.communication");
207 public void handleRemoval() {
208 // delete token for openHAB
209 ContentResponse deleteTokenResponse;
211 Request deleteTokenRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_DELETE_USER,
213 deleteTokenResponse = OpenAPIUtils.sendOpenAPIRequest(deleteTokenRequest);
214 if (deleteTokenResponse.getStatus() != HttpStatus.NO_CONTENT_204) {
215 logger.warn("Failed to delete token for openHAB. Response code is {}", deleteTokenResponse.getStatus());
218 logger.debug("Successfully deleted token for openHAB from controller");
219 } catch (NanoleafUnauthorizedException e) {
220 logger.warn("Attempt to delete token for openHAB failed. Token unauthorized.");
221 } catch (NanoleafException ne) {
222 logger.warn("Attempt to delete token for openHAB failed : {}", ne.getMessage());
225 super.handleRemoval();
226 logger.debug("Nanoleaf controller removed");
230 public void dispose() {
233 logger.debug("Disposing handler for Nanoleaf controller {}", getThing().getUID());
236 public boolean registerControllerListener(NanoleafControllerListener controllerListener) {
237 logger.debug("Register new listener for controller {}", getThing().getUID());
238 boolean result = controllerListeners.add(controllerListener);
240 startPanelDiscoveryJob();
245 public boolean unregisterControllerListener(NanoleafControllerListener controllerListener) {
246 logger.debug("Unregister listener for controller {}", getThing().getUID());
247 boolean result = controllerListeners.remove(controllerListener);
249 stopPanelDiscoveryJob();
254 public NanoleafControllerConfig getControllerConfig() {
255 NanoleafControllerConfig config = new NanoleafControllerConfig();
256 config.address = this.getAddress();
257 config.port = this.getPort();
258 config.refreshInterval = this.getRefreshIntervall();
259 config.authToken = this.getAuthToken();
260 config.deviceType = this.getDeviceType();
264 public synchronized void startPairingJob() {
265 if (pairingJob == null || pairingJob.isCancelled()) {
266 logger.debug("Start pairing job, interval={} sec", PAIRING_INTERVAL);
267 pairingJob = scheduler.scheduleWithFixedDelay(this::runPairing, 0, PAIRING_INTERVAL, TimeUnit.SECONDS);
271 private synchronized void stopPairingJob() {
272 if (pairingJob != null && !pairingJob.isCancelled()) {
273 logger.debug("Stop pairing job");
274 pairingJob.cancel(true);
275 this.pairingJob = null;
279 private synchronized void startUpdateJob() {
280 if (StringUtils.isNotEmpty(getAuthToken())) {
281 if (updateJob == null || updateJob.isCancelled()) {
282 logger.debug("Start controller status job, repeat every {} sec", getRefreshIntervall());
283 updateJob = scheduler.scheduleWithFixedDelay(this::runUpdate, 0, getRefreshIntervall(),
287 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
288 "@text/error.nanoleaf.controller.noToken");
292 private synchronized void stopUpdateJob() {
293 if (updateJob != null && !updateJob.isCancelled()) {
294 logger.debug("Stop status job");
295 updateJob.cancel(true);
296 this.updateJob = null;
300 public synchronized void startPanelDiscoveryJob() {
301 logger.debug("Starting panel discovery job. Has Controller-Listeners: {} panelDiscoveryJob: {}",
302 !controllerListeners.isEmpty(), panelDiscoveryJob);
303 if (!controllerListeners.isEmpty() && (panelDiscoveryJob == null || panelDiscoveryJob.isCancelled())) {
304 logger.debug("Start panel discovery job, interval={} sec", PANEL_DISCOVERY_INTERVAL);
305 panelDiscoveryJob = scheduler.scheduleWithFixedDelay(this::runPanelDiscovery, 0, PANEL_DISCOVERY_INTERVAL,
310 private synchronized void stopPanelDiscoveryJob() {
311 if (controllerListeners.isEmpty() && panelDiscoveryJob != null && !panelDiscoveryJob.isCancelled()) {
312 logger.debug("Stop panel discovery job");
313 panelDiscoveryJob.cancel(true);
314 this.panelDiscoveryJob = null;
318 private synchronized void startTouchJob() {
319 NanoleafControllerConfig config = getConfigAs(NanoleafControllerConfig.class);
320 if (!config.deviceType.equals(DEVICE_TYPE_CANVAS)) {
321 logger.debug("NOT starting TouchJob for Panel {} because it has wrong device type '{}' vs required '{}'",
322 this.getThing().getUID(), config.deviceType, DEVICE_TYPE_CANVAS);
325 logger.debug("Starting TouchJob for Panel {}", this.getThing().getUID());
327 if (StringUtils.isNotEmpty(getAuthToken())) {
328 if (touchJob == null || touchJob.isCancelled()) {
329 logger.debug("Starting Touchjob now");
330 touchJob = scheduler.schedule(this::runTouchDetection, 0, TimeUnit.SECONDS);
333 logger.error("starting TouchJob for Controller {} failed - missing token", this.getThing().getUID());
337 private synchronized void stopTouchJob() {
338 if (touchJob != null && !touchJob.isCancelled()) {
339 logger.debug("Stop touch job");
340 touchJob.cancel(true);
341 this.touchJob = null;
345 private void runUpdate() {
346 logger.debug("Run update job");
348 updateFromControllerInfo();
349 startTouchJob(); // if device type has changed, start touch detection.
350 // controller might have been offline, e.g. for firmware update. In this case, return to online state
351 if (ThingStatus.OFFLINE.equals(getThing().getStatus())) {
352 logger.debug("Controller {} is back online", thing.getUID());
353 updateStatus(ThingStatus.ONLINE);
355 } catch (NanoleafUnauthorizedException nae) {
356 logger.warn("Status update unauthorized: {}", nae.getMessage());
357 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
358 "@text/error.nanoleaf.controller.invalidToken");
359 if (StringUtils.isEmpty(getAuthToken())) {
360 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
361 "@text/error.nanoleaf.controller.noToken");
363 } catch (NanoleafException ne) {
364 logger.warn("Status update failed: {}", ne.getMessage());
365 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
366 "@text/error.nanoleaf.controller.communication");
367 } catch (RuntimeException e) {
368 logger.warn("Update job failed", e);
369 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/error.nanoleaf.controller.runtime");
373 private void runPairing() {
374 logger.debug("Run pairing job");
376 if (StringUtils.isNotEmpty(getAuthToken())) {
377 if (pairingJob != null) {
378 pairingJob.cancel(false);
380 logger.debug("Authentication token found. Canceling pairing job");
383 ContentResponse authTokenResponse = OpenAPIUtils
384 .requestBuilder(httpClient, getControllerConfig(), API_ADD_USER, HttpMethod.POST).send();
385 if (logger.isTraceEnabled()) {
386 logger.trace("Auth token response: {}", authTokenResponse.getContentAsString());
389 if (authTokenResponse.getStatus() != HttpStatus.OK_200) {
390 logger.debug("Pairing pending for {}. Controller returns status code {}", this.getThing().getUID(),
391 authTokenResponse.getStatus());
393 // get auth token from response
395 AuthToken authToken = gson.fromJson(authTokenResponse.getContentAsString(), AuthToken.class);
397 if (StringUtils.isNotEmpty(authToken.getAuthToken())) {
398 logger.debug("Pairing succeeded.");
400 // Update and save the auth token in the thing configuration
401 Configuration config = editConfiguration();
402 config.put(NanoleafControllerConfig.AUTH_TOKEN, authToken.getAuthToken());
403 updateConfiguration(config);
405 updateStatus(ThingStatus.ONLINE);
406 // Update local field
407 setAuthToken(authToken.getAuthToken());
411 startPanelDiscoveryJob();
414 logger.debug("No auth token found in response: {}", authTokenResponse.getContentAsString());
415 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
416 "@text/error.nanoleaf.controller.pairingFailed");
417 throw new NanoleafException(authTokenResponse.getContentAsString());
420 } catch (JsonSyntaxException e) {
421 logger.warn("Received invalid data", e);
422 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
423 "@text/error.nanoleaf.controller.invalidData");
424 } catch (NanoleafException e) {
425 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR,
426 "@text/error.nanoleaf.controller.noTokenReceived");
427 } catch (InterruptedException | ExecutionException | TimeoutException e) {
428 logger.warn("Cannot send authorization request to controller: ", e);
429 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
430 "@text/error.nanoleaf.controller.authRequest");
431 } catch (RuntimeException e) {
432 logger.warn("Pairing job failed", e);
433 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/error.nanoleaf.controller.runtime");
434 } catch (Exception e) {
435 logger.warn("Cannot start http client", e);
436 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
437 "@text/error.nanoleaf.controller.noClient");
441 private void runPanelDiscovery() {
442 logger.debug("Run panel discovery job");
443 // Trigger a new discovery of connected panels
444 for (NanoleafControllerListener controllerListener : controllerListeners) {
446 controllerListener.onControllerInfoFetched(getThing().getUID(), receiveControllerInfo());
447 } catch (NanoleafUnauthorizedException nue) {
448 logger.warn("Panel discovery unauthorized: {}", nue.getMessage());
449 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
450 "@text/error.nanoleaf.controller.invalidToken");
451 if (StringUtils.isEmpty(getAuthToken())) {
452 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
453 "@text/error.nanoleaf.controller.noToken");
455 } catch (NanoleafInterruptedException nie) {
456 logger.info("Panel discovery has been stopped.");
457 } catch (NanoleafException ne) {
458 logger.warn("Failed to discover panels: ", ne);
459 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
460 "@text/error.nanoleaf.controller.communication");
461 } catch (RuntimeException e) {
462 logger.warn("Panel discovery job failed", e);
463 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.NONE, "@text/error.nanoleaf.controller.runtime");
469 * This is based on the touch event detection described in https://forum.nanoleaf.me/docs/openapi#_842h3097vbgq
471 private static boolean touchJobRunning = false;
473 private void runTouchDetection() {
474 if (touchJobRunning) {
475 logger.debug("touch job already running. quitting.");
479 touchJobRunning = true;
480 URI eventUri = OpenAPIUtils.getUri(getControllerConfig(), API_EVENTS, "id=4");
481 logger.debug("touch job registered on: {}", eventUri.toString());
482 httpClient.newRequest(eventUri).send(new Response.Listener.Adapter() // request runs forever
485 public void onContent(@Nullable Response response, @Nullable ByteBuffer content) {
486 String s = StandardCharsets.UTF_8.decode(content).toString();
487 logger.trace("content {}", s);
489 Scanner eventContent = new Scanner(s);
490 while (eventContent.hasNextLine()) {
491 String line = eventContent.nextLine().trim();
492 // we don't expect anything than content id:4, so we do not check that but only care about the
494 if (line.startsWith("data:")) {
495 String json = line.substring(5).trim(); // supposed to be JSON
497 TouchEvents touchEvents = gson.fromJson(json, TouchEvents.class);
498 handleTouchEvents(Objects.requireNonNull(touchEvents));
499 } catch (JsonSyntaxException jse) {
500 logger.error("couldn't parse touch event json {}", json);
504 eventContent.close();
505 logger.debug("leaving touch onContent");
506 super.onContent(response, content);
510 public void onSuccess(@Nullable Response response) {
511 logger.trace("touch event SUCCESS: {}", response);
515 public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
516 logger.trace("touch event FAILURE: {}", response);
520 public void onComplete(@Nullable Result result) {
521 logger.trace("touch event COMPLETE: {}", result);
524 } catch (RuntimeException | NanoleafException e) {
525 logger.warn("setting up TouchDetection failed", e);
527 touchJobRunning = false;
529 logger.debug("leaving run touch detection");
533 * Interate over all gathered touch events and apply them to the panel they belong to
537 private void handleTouchEvents(TouchEvents touchEvents) {
538 touchEvents.getEvents().forEach(event -> {
539 logger.info("panel: {} gesture id: {}", event.getPanelId(), event.getGesture());
541 // Iterate over all child things = all panels of that controller
542 this.getThing().getThings().forEach(child -> {
543 NanoleafPanelHandler panelHandler = (NanoleafPanelHandler) child.getHandler();
544 if (panelHandler != null) {
545 logger.trace("Checking available panel -{}- versus event panel -{}-", panelHandler.getPanelID(),
547 if (panelHandler.getPanelID().equals(event.getPanelId())) {
548 logger.debug("Panel {} found. Triggering item with gesture {}.", panelHandler.getPanelID(),
550 panelHandler.updatePanelGesture(event.getGesture());
557 private void updateFromControllerInfo() throws NanoleafException {
558 logger.debug("Update channels for controller {}", thing.getUID());
559 this.controllerInfo = receiveControllerInfo();
560 if (controllerInfo == null) {
561 logger.debug("No Controller Info has been provided");
564 final State state = controllerInfo.getState();
566 OnOffType powerState = state.getOnOff();
567 updateState(CHANNEL_POWER, powerState);
570 Ct colorTemperature = state.getColorTemperature();
572 float colorTempPercent = 0f;
573 if (colorTemperature != null) {
574 updateState(CHANNEL_COLOR_TEMPERATURE_ABS, new DecimalType(colorTemperature.getValue()));
577 Integer min = colorTemperature.getMin();
578 int colorMin = (min == null) ? 0 : min;
581 Integer max = colorTemperature.getMax();
582 int colorMax = (max == null) ? 0 : max;
584 colorTempPercent = (colorTemperature.getValue() - colorMin) / (colorMax - colorMin)
585 * PercentType.HUNDRED.intValue();
588 updateState(CHANNEL_COLOR_TEMPERATURE, new PercentType(Float.toString(colorTempPercent)));
589 updateState(CHANNEL_EFFECT, new StringType(controllerInfo.getEffects().getSelect()));
592 Hue stateHue = state.getHue();
593 int hue = (stateHue != null) ? stateHue.getValue() : 0;
595 Sat stateSaturation = state.getSaturation();
596 int saturation = (stateSaturation != null) ? stateSaturation.getValue() : 0;
598 Brightness stateBrightness = state.getBrightness();
599 int brightness = (stateBrightness != null) ? stateBrightness.getValue() : 0;
601 updateState(CHANNEL_COLOR, new HSBType(new DecimalType(hue), new PercentType(saturation),
602 new PercentType(powerState == OnOffType.ON ? brightness : 0)));
603 updateState(CHANNEL_COLOR_MODE, new StringType(state.getColorMode()));
604 updateState(CHANNEL_RHYTHM_ACTIVE, controllerInfo.getRhythm().getRhythmActive() ? OnOffType.ON : OnOffType.OFF);
605 updateState(CHANNEL_RHYTHM_MODE, new DecimalType(controllerInfo.getRhythm().getRhythmMode()));
606 updateState(CHANNEL_RHYTHM_STATE,
607 controllerInfo.getRhythm().getRhythmConnected() ? OnOffType.ON : OnOffType.OFF);
608 // update bridge properties which may have changed, or are not present during discovery
609 Map<String, String> properties = editProperties();
610 properties.put(Thing.PROPERTY_SERIAL_NUMBER, controllerInfo.getSerialNo());
611 properties.put(Thing.PROPERTY_FIRMWARE_VERSION, controllerInfo.getFirmwareVersion());
612 properties.put(Thing.PROPERTY_MODEL_ID, controllerInfo.getModel());
613 properties.put(Thing.PROPERTY_VENDOR, controllerInfo.getManufacturer());
614 updateProperties(properties);
616 Configuration config = editConfiguration();
618 if (MODEL_ID_CANVAS.equals(controllerInfo.getModel())) {
619 config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_CANVAS);
620 logger.debug("Set to device type {}", DEVICE_TYPE_CANVAS);
622 config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_LIGHTPANELS);
623 logger.debug("Set to device type {}", DEVICE_TYPE_LIGHTPANELS);
625 updateConfiguration(config);
627 getConfig().getProperties().forEach((key, value) -> {
628 logger.trace("Configuration property: key {} value {}", key, value);
631 getThing().getProperties().forEach((key, value) -> {
632 logger.debug("Thing property: key {} value {}", key, value);
635 // update the color channels of each panel
636 this.getThing().getThings().forEach(child -> {
637 NanoleafPanelHandler panelHandler = (NanoleafPanelHandler) child.getHandler();
638 if (panelHandler != null) {
639 logger.debug("Update color channel for panel {}", panelHandler.getThing().getUID());
640 panelHandler.updatePanelColorChannel();
645 private ControllerInfo receiveControllerInfo() throws NanoleafException, NanoleafUnauthorizedException {
646 ContentResponse controllerlInfoJSON = OpenAPIUtils.sendOpenAPIRequest(OpenAPIUtils.requestBuilder(httpClient,
647 getControllerConfig(), API_GET_CONTROLLER_INFO, HttpMethod.GET));
648 ControllerInfo controllerInfo = gson.fromJson(controllerlInfoJSON.getContentAsString(), ControllerInfo.class);
649 return Objects.requireNonNull(controllerInfo);
652 private void sendStateCommand(String channel, Command command) throws NanoleafException {
653 State stateObject = new State();
656 if (command instanceof OnOffType) {
657 // On/Off command - turns controller on/off
658 BooleanState state = new On();
659 state.setValue(OnOffType.ON.equals(command));
660 stateObject.setState(state);
662 logger.warn("Unhandled command type: {}", command.getClass().getName());
667 if (command instanceof OnOffType) {
668 // On/Off command - turns controller on/off
669 BooleanState state = new On();
670 state.setValue(OnOffType.ON.equals(command));
671 stateObject.setState(state);
672 } else if (command instanceof HSBType) {
673 // regular color HSB command
674 IntegerState h = new Hue();
675 IntegerState s = new Sat();
676 IntegerState b = new Brightness();
677 h.setValue(((HSBType) command).getHue().intValue());
678 s.setValue(((HSBType) command).getSaturation().intValue());
679 b.setValue(((HSBType) command).getBrightness().intValue());
680 stateObject.setState(h);
681 stateObject.setState(s);
682 stateObject.setState(b);
683 } else if (command instanceof PercentType) {
684 // brightness command
685 IntegerState b = new Brightness();
686 b.setValue(((PercentType) command).intValue());
687 stateObject.setState(b);
688 } else if (command instanceof IncreaseDecreaseType) {
689 // increase/decrease brightness
690 if (controllerInfo != null) {
692 Brightness brightness = controllerInfo.getState().getBrightness();
693 int brightnessMin = 0;
694 int brightnessMax = 0;
695 if (brightness != null) {
697 Integer min = brightness.getMin();
698 brightnessMin = (min == null) ? 0 : min;
700 Integer max = brightness.getMax();
701 brightnessMax = (max == null) ? 0 : max;
703 if (IncreaseDecreaseType.INCREASE.equals(command)) {
705 Math.min(brightnessMax, brightness.getValue() + BRIGHTNESS_STEP_SIZE));
708 Math.max(brightnessMin, brightness.getValue() - BRIGHTNESS_STEP_SIZE));
710 stateObject.setState(brightness);
711 logger.debug("Setting controller brightness to {}", brightness.getValue());
712 // update controller info in case new command is sent before next update job interval
713 controllerInfo.getState().setBrightness(brightness);
715 logger.debug("Couldn't set brightness as it was null!");
719 logger.warn("Unhandled command type: {}", command.getClass().getName());
723 case CHANNEL_COLOR_TEMPERATURE:
724 if (command instanceof PercentType) {
725 // Color temperature (percent)
726 IntegerState state = new Ct();
728 Ct colorTemperature = controllerInfo.getState().getColorTemperature();
732 if (colorTemperature != null) {
734 Integer min = colorTemperature.getMin();
735 colorMin = (min == null) ? 0 : min;
738 Integer max = colorTemperature.getMax();
739 colorMax = (max == null) ? 0 : max;
742 state.setValue(Math.round((colorMax - colorMin) * ((PercentType) command).intValue()
743 / PercentType.HUNDRED.floatValue() + colorMin));
744 stateObject.setState(state);
746 logger.warn("Unhandled command type: {}", command.getClass().getName());
750 case CHANNEL_COLOR_TEMPERATURE_ABS:
751 if (command instanceof DecimalType) {
752 // Color temperature (absolute)
753 IntegerState state = new Ct();
754 state.setValue(((DecimalType) command).intValue());
755 stateObject.setState(state);
757 logger.warn("Unhandled command type: {}", command.getClass().getName());
761 case CHANNEL_PANEL_LAYOUT:
763 Layout layout = controllerInfo.getPanelLayout().getLayout();
764 String layoutView = (layout != null) ? layout.getLayoutView() : "";
765 logger.info("Panel layout and ids for controller {} \n{}", thing.getUID(), layoutView);
766 updateState(CHANNEL_PANEL_LAYOUT, OnOffType.OFF);
769 logger.warn("Unhandled command type: {}", command.getClass().getName());
773 Request setNewStateRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_SET_VALUE,
775 setNewStateRequest.content(new StringContentProvider(gson.toJson(stateObject)), "application/json");
776 OpenAPIUtils.sendOpenAPIRequest(setNewStateRequest);
779 private void sendEffectCommand(Command command) throws NanoleafException {
780 Effects effects = new Effects();
781 if (command instanceof StringType) {
782 effects.setSelect(command.toString());
784 logger.warn("Unhandled command type: {}", command.getClass().getName());
787 Request setNewEffectRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_EFFECT,
789 String content = gson.toJson(effects);
790 logger.debug("sending effect command from controller {}: {}", getThing().getUID(), content);
791 setNewEffectRequest.content(new StringContentProvider(content), "application/json");
792 OpenAPIUtils.sendOpenAPIRequest(setNewEffectRequest);
795 private void sendRhythmCommand(Command command) throws NanoleafException {
796 Rhythm rhythm = new Rhythm();
797 if (command instanceof DecimalType) {
798 rhythm.setRhythmMode(((DecimalType) command).intValue());
800 logger.warn("Unhandled command type: {}", command.getClass().getName());
803 Request setNewRhythmRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_RHYTHM_MODE,
805 setNewRhythmRequest.content(new StringContentProvider(gson.toJson(rhythm)), "application/json");
806 OpenAPIUtils.sendOpenAPIRequest(setNewRhythmRequest);
809 private String getAddress() {
810 return StringUtils.defaultString(this.address);
813 private void setAddress(String address) {
814 this.address = address;
817 private int getPort() {
821 private void setPort(int port) {
825 private int getRefreshIntervall() {
826 return refreshIntervall;
829 private void setRefreshIntervall(int refreshIntervall) {
830 this.refreshIntervall = refreshIntervall;
833 private String getAuthToken() {
834 return StringUtils.defaultString(authToken);
837 private void setAuthToken(@Nullable String authToken) {
838 this.authToken = authToken;
841 private String getDeviceType() {
842 return StringUtils.defaultString(deviceType);
845 private void setDeviceType(String deviceType) {
846 this.deviceType = deviceType;
849 private void stopAllJobs() {
852 stopPanelDiscoveryJob();