]> git.basschouten.com Git - openhab-addons.git/blob
ddfdb9a14f1cf3efa5e60d63573eb4c99c61b3e9
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2020 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.nanoleaf.internal.handler;
14
15 import static org.openhab.binding.nanoleaf.internal.NanoleafBindingConstants.*;
16
17 import java.net.URI;
18 import java.nio.ByteBuffer;
19 import java.nio.charset.StandardCharsets;
20 import java.util.List;
21 import java.util.Map;
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;
29
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;
61
62 import com.google.gson.Gson;
63 import com.google.gson.JsonSyntaxException;
64
65 /**
66  * The {@link NanoleafControllerHandler} is responsible for handling commands to the controller which
67  * affect all panels connected to it (e.g. selected effect)
68  *
69  * @author Martin Raepple - Initial contribution
70  * @author Stefan Höhn - Canvas Touch Support
71  */
72 @NonNullByDefault
73 public class NanoleafControllerHandler extends BaseBridgeHandler {
74
75     // Pairing interval in seconds
76     private static final int PAIRING_INTERVAL = 25;
77
78     // Panel discovery interval in seconds
79     private static final int PANEL_DISCOVERY_INTERVAL = 30;
80
81     private final Logger logger = LoggerFactory.getLogger(NanoleafControllerHandler.class);
82     private HttpClient httpClient;
83     private List<NanoleafControllerListener> controllerListeners = new CopyOnWriteArrayList<>();
84
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;
90
91     // JSON parser for API responses
92     private final Gson gson = new Gson();
93
94     // Controller configuration settings and channel values
95     private @Nullable String address;
96     private int port;
97     private int refreshIntervall;
98     private @Nullable String authToken;
99     private @Nullable String deviceType;
100     private @NonNullByDefault({}) ControllerInfo controllerInfo;
101
102     public NanoleafControllerHandler(Bridge bridge, HttpClient httpClient) {
103         super(bridge);
104         this.httpClient = httpClient;
105     }
106
107     @Override
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);
116
117         @Nullable
118         String property = getThing().getProperties().get(Thing.PROPERTY_MODEL_ID);
119         if (MODEL_ID_CANVAS.equals(property)) {
120             config.deviceType = DEVICE_TYPE_CANVAS;
121         } else {
122             config.deviceType = DEVICE_TYPE_LIGHTPANELS;
123         }
124         setDeviceType(config.deviceType);
125
126         try {
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");
132                 stopAllJobs();
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");
140                 stopAllJobs();
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");
145                 startPairingJob();
146                 stopUpdateJob();
147                 stopPanelDiscoveryJob();
148             } else {
149                 logger.debug("Controller is online. Stop pairing job, start update & panel discovery jobs");
150                 updateStatus(ThingStatus.ONLINE);
151                 stopPairingJob();
152                 startUpdateJob();
153                 startPanelDiscoveryJob();
154                 startTouchJob();
155             }
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");
161         }
162     }
163
164     @Override
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.");
169             return;
170         }
171         try {
172             if (command instanceof RefreshType) {
173                 updateFromControllerInfo();
174             } else {
175                 switch (channelUID.getId()) {
176                     case CHANNEL_POWER:
177                     case CHANNEL_COLOR:
178                     case CHANNEL_COLOR_TEMPERATURE:
179                     case CHANNEL_COLOR_TEMPERATURE_ABS:
180                     case CHANNEL_PANEL_LAYOUT:
181                         sendStateCommand(channelUID.getId(), command);
182                         break;
183                     case CHANNEL_EFFECT:
184                         sendEffectCommand(command);
185                         break;
186                     case CHANNEL_RHYTHM_MODE:
187                         sendRhythmCommand(command);
188                         break;
189                     default:
190                         logger.warn("Channel with id {} not handled", channelUID.getId());
191                         break;
192                 }
193             }
194         } catch (NanoleafUnauthorizedException nae) {
195             logger.warn("Authorization for command {} to channelUID {} failed: {}", command, channelUID,
196                     nae.getMessage());
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");
203         }
204     }
205
206     @Override
207     public void handleRemoval() {
208         // delete token for openHAB
209         ContentResponse deleteTokenResponse;
210         try {
211             Request deleteTokenRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_DELETE_USER,
212                     HttpMethod.DELETE);
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());
216                 return;
217             }
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());
223         }
224         stopAllJobs();
225         super.handleRemoval();
226         logger.debug("Nanoleaf controller removed");
227     }
228
229     @Override
230     public void dispose() {
231         stopAllJobs();
232         super.dispose();
233         logger.debug("Disposing handler for Nanoleaf controller {}", getThing().getUID());
234     }
235
236     public boolean registerControllerListener(NanoleafControllerListener controllerListener) {
237         logger.debug("Register new listener for controller {}", getThing().getUID());
238         boolean result = controllerListeners.add(controllerListener);
239         if (result) {
240             startPanelDiscoveryJob();
241         }
242         return result;
243     }
244
245     public boolean unregisterControllerListener(NanoleafControllerListener controllerListener) {
246         logger.debug("Unregister listener for controller {}", getThing().getUID());
247         boolean result = controllerListeners.remove(controllerListener);
248         if (result) {
249             stopPanelDiscoveryJob();
250         }
251         return result;
252     }
253
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();
261         return config;
262     }
263
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);
268         }
269     }
270
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;
276         }
277     }
278
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(),
284                         TimeUnit.SECONDS);
285             }
286         } else {
287             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
288                     "@text/error.nanoleaf.controller.noToken");
289         }
290     }
291
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;
297         }
298     }
299
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,
306                     TimeUnit.SECONDS);
307         }
308     }
309
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;
315         }
316     }
317
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);
323             return;
324         } else
325             logger.debug("Starting TouchJob for Panel {}", this.getThing().getUID());
326
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);
331             }
332         } else {
333             logger.error("starting TouchJob for Controller {} failed - missing token", this.getThing().getUID());
334         }
335     }
336
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;
342         }
343     }
344
345     private void runUpdate() {
346         logger.debug("Run update job");
347         try {
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);
354             }
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");
362             }
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");
370         }
371     }
372
373     private void runPairing() {
374         logger.debug("Run pairing job");
375         try {
376             if (StringUtils.isNotEmpty(getAuthToken())) {
377                 if (pairingJob != null) {
378                     pairingJob.cancel(false);
379                 }
380                 logger.debug("Authentication token found. Canceling pairing job");
381                 return;
382             }
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());
387             }
388
389             if (authTokenResponse.getStatus() != HttpStatus.OK_200) {
390                 logger.debug("Pairing pending for {}. Controller returns status code {}", this.getThing().getUID(),
391                         authTokenResponse.getStatus());
392             } else {
393                 // get auth token from response
394                 @Nullable
395                 AuthToken authToken = gson.fromJson(authTokenResponse.getContentAsString(), AuthToken.class);
396
397                 if (StringUtils.isNotEmpty(authToken.getAuthToken())) {
398                     logger.debug("Pairing succeeded.");
399
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);
404
405                     updateStatus(ThingStatus.ONLINE);
406                     // Update local field
407                     setAuthToken(authToken.getAuthToken());
408
409                     stopPairingJob();
410                     startUpdateJob();
411                     startPanelDiscoveryJob();
412                     startTouchJob();
413                 } else {
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());
418                 }
419             }
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");
438         }
439     }
440
441     private void runPanelDiscovery() {
442         logger.debug("Run panel discovery job");
443         // Trigger a new discovery of connected panels
444         for (NanoleafControllerListener controllerListener : controllerListeners) {
445             try {
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");
454                 }
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");
464             }
465         }
466     }
467
468     /**
469      * This is based on the touch event detection described in https://forum.nanoleaf.me/docs/openapi#_842h3097vbgq
470      */
471     private static boolean touchJobRunning = false;
472
473     private void runTouchDetection() {
474         if (touchJobRunning) {
475             logger.debug("touch job already running. quitting.");
476             return;
477         }
478         try {
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
483             {
484                 @Override
485                 public void onContent(@Nullable Response response, @Nullable ByteBuffer content) {
486                     String s = StandardCharsets.UTF_8.decode(content).toString();
487                     logger.trace("content {}", s);
488
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
493                         // data part
494                         if (line.startsWith("data:")) {
495                             String json = line.substring(5).trim(); // supposed to be JSON
496                             try {
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);
501                             }
502                         }
503                     }
504                     eventContent.close();
505                     logger.debug("leaving touch onContent");
506                     super.onContent(response, content);
507                 }
508
509                 @Override
510                 public void onSuccess(@Nullable Response response) {
511                     logger.trace("touch event SUCCESS: {}", response);
512                 }
513
514                 @Override
515                 public void onFailure(@Nullable Response response, @Nullable Throwable failure) {
516                     logger.trace("touch event FAILURE: {}", response);
517                 }
518
519                 @Override
520                 public void onComplete(@Nullable Result result) {
521                     logger.trace("touch event COMPLETE: {}", result);
522                 }
523             });
524         } catch (RuntimeException | NanoleafException e) {
525             logger.warn("setting up TouchDetection failed", e);
526         } finally {
527             touchJobRunning = false;
528         }
529         logger.debug("leaving run touch detection");
530     }
531
532     /**
533      * Interate over all gathered touch events and apply them to the panel they belong to
534      *
535      * @param touchEvents
536      */
537     private void handleTouchEvents(TouchEvents touchEvents) {
538         touchEvents.getEvents().forEach(event -> {
539             logger.info("panel: {} gesture id: {}", event.getPanelId(), event.getGesture());
540
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(),
546                             event.getPanelId());
547                     if (panelHandler.getPanelID().equals(event.getPanelId())) {
548                         logger.debug("Panel {} found. Triggering item with gesture {}.", panelHandler.getPanelID(),
549                                 event.getGesture());
550                         panelHandler.updatePanelGesture(event.getGesture());
551                     }
552                 }
553             });
554         });
555     }
556
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");
562             return;
563         }
564         final State state = controllerInfo.getState();
565
566         OnOffType powerState = state.getOnOff();
567         updateState(CHANNEL_POWER, powerState);
568
569         @Nullable
570         Ct colorTemperature = state.getColorTemperature();
571
572         float colorTempPercent = 0f;
573         if (colorTemperature != null) {
574             updateState(CHANNEL_COLOR_TEMPERATURE_ABS, new DecimalType(colorTemperature.getValue()));
575
576             @Nullable
577             Integer min = colorTemperature.getMin();
578             int colorMin = (min == null) ? 0 : min;
579
580             @Nullable
581             Integer max = colorTemperature.getMax();
582             int colorMax = (max == null) ? 0 : max;
583
584             colorTempPercent = (colorTemperature.getValue() - colorMin) / (colorMax - colorMin)
585                     * PercentType.HUNDRED.intValue();
586         }
587
588         updateState(CHANNEL_COLOR_TEMPERATURE, new PercentType(Float.toString(colorTempPercent)));
589         updateState(CHANNEL_EFFECT, new StringType(controllerInfo.getEffects().getSelect()));
590
591         @Nullable
592         Hue stateHue = state.getHue();
593         int hue = (stateHue != null) ? stateHue.getValue() : 0;
594         @Nullable
595         Sat stateSaturation = state.getSaturation();
596         int saturation = (stateSaturation != null) ? stateSaturation.getValue() : 0;
597         @Nullable
598         Brightness stateBrightness = state.getBrightness();
599         int brightness = (stateBrightness != null) ? stateBrightness.getValue() : 0;
600
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);
615
616         Configuration config = editConfiguration();
617
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);
621         } else {
622             config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_LIGHTPANELS);
623             logger.debug("Set to device type {}", DEVICE_TYPE_LIGHTPANELS);
624         }
625         updateConfiguration(config);
626
627         getConfig().getProperties().forEach((key, value) -> {
628             logger.trace("Configuration property: key {} value {}", key, value);
629         });
630
631         getThing().getProperties().forEach((key, value) -> {
632             logger.debug("Thing property:  key {} value {}", key, value);
633         });
634
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();
641             }
642         });
643     }
644
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);
650     }
651
652     private void sendStateCommand(String channel, Command command) throws NanoleafException {
653         State stateObject = new State();
654         switch (channel) {
655             case CHANNEL_POWER:
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);
661                 } else {
662                     logger.warn("Unhandled command type: {}", command.getClass().getName());
663                     return;
664                 }
665                 break;
666             case CHANNEL_COLOR:
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) {
691                         @Nullable
692                         Brightness brightness = controllerInfo.getState().getBrightness();
693                         int brightnessMin = 0;
694                         int brightnessMax = 0;
695                         if (brightness != null) {
696                             @Nullable
697                             Integer min = brightness.getMin();
698                             brightnessMin = (min == null) ? 0 : min;
699                             @Nullable
700                             Integer max = brightness.getMax();
701                             brightnessMax = (max == null) ? 0 : max;
702
703                             if (IncreaseDecreaseType.INCREASE.equals(command)) {
704                                 brightness.setValue(
705                                         Math.min(brightnessMax, brightness.getValue() + BRIGHTNESS_STEP_SIZE));
706                             } else {
707                                 brightness.setValue(
708                                         Math.max(brightnessMin, brightness.getValue() - BRIGHTNESS_STEP_SIZE));
709                             }
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);
714                         } else {
715                             logger.debug("Couldn't set brightness as it was null!");
716                         }
717                     }
718                 } else {
719                     logger.warn("Unhandled command type: {}", command.getClass().getName());
720                     return;
721                 }
722                 break;
723             case CHANNEL_COLOR_TEMPERATURE:
724                 if (command instanceof PercentType) {
725                     // Color temperature (percent)
726                     IntegerState state = new Ct();
727                     @Nullable
728                     Ct colorTemperature = controllerInfo.getState().getColorTemperature();
729
730                     int colorMin = 0;
731                     int colorMax = 0;
732                     if (colorTemperature != null) {
733                         @Nullable
734                         Integer min = colorTemperature.getMin();
735                         colorMin = (min == null) ? 0 : min;
736
737                         @Nullable
738                         Integer max = colorTemperature.getMax();
739                         colorMax = (max == null) ? 0 : max;
740                     }
741
742                     state.setValue(Math.round((colorMax - colorMin) * ((PercentType) command).intValue()
743                             / PercentType.HUNDRED.floatValue() + colorMin));
744                     stateObject.setState(state);
745                 } else {
746                     logger.warn("Unhandled command type: {}", command.getClass().getName());
747                     return;
748                 }
749                 break;
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);
756                 } else {
757                     logger.warn("Unhandled command type: {}", command.getClass().getName());
758                     return;
759                 }
760                 break;
761             case CHANNEL_PANEL_LAYOUT:
762                 @Nullable
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);
767                 break;
768             default:
769                 logger.warn("Unhandled command type: {}", command.getClass().getName());
770                 return;
771         }
772
773         Request setNewStateRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_SET_VALUE,
774                 HttpMethod.PUT);
775         setNewStateRequest.content(new StringContentProvider(gson.toJson(stateObject)), "application/json");
776         OpenAPIUtils.sendOpenAPIRequest(setNewStateRequest);
777     }
778
779     private void sendEffectCommand(Command command) throws NanoleafException {
780         Effects effects = new Effects();
781         if (command instanceof StringType) {
782             effects.setSelect(command.toString());
783         } else {
784             logger.warn("Unhandled command type: {}", command.getClass().getName());
785             return;
786         }
787         Request setNewEffectRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_EFFECT,
788                 HttpMethod.PUT);
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);
793     }
794
795     private void sendRhythmCommand(Command command) throws NanoleafException {
796         Rhythm rhythm = new Rhythm();
797         if (command instanceof DecimalType) {
798             rhythm.setRhythmMode(((DecimalType) command).intValue());
799         } else {
800             logger.warn("Unhandled command type: {}", command.getClass().getName());
801             return;
802         }
803         Request setNewRhythmRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_RHYTHM_MODE,
804                 HttpMethod.PUT);
805         setNewRhythmRequest.content(new StringContentProvider(gson.toJson(rhythm)), "application/json");
806         OpenAPIUtils.sendOpenAPIRequest(setNewRhythmRequest);
807     }
808
809     private String getAddress() {
810         return StringUtils.defaultString(this.address);
811     }
812
813     private void setAddress(String address) {
814         this.address = address;
815     }
816
817     private int getPort() {
818         return port;
819     }
820
821     private void setPort(int port) {
822         this.port = port;
823     }
824
825     private int getRefreshIntervall() {
826         return refreshIntervall;
827     }
828
829     private void setRefreshIntervall(int refreshIntervall) {
830         this.refreshIntervall = refreshIntervall;
831     }
832
833     private String getAuthToken() {
834         return StringUtils.defaultString(authToken);
835     }
836
837     private void setAuthToken(@Nullable String authToken) {
838         this.authToken = authToken;
839     }
840
841     private String getDeviceType() {
842         return StringUtils.defaultString(deviceType);
843     }
844
845     private void setDeviceType(String deviceType) {
846         this.deviceType = deviceType;
847     }
848
849     private void stopAllJobs() {
850         stopPairingJob();
851         stopUpdateJob();
852         stopPanelDiscoveryJob();
853         stopTouchJob();
854     }
855 }