]> git.basschouten.com Git - openhab-addons.git/blob
162e95e91efe64fdaae8e3bd7e44d1b8b625fbb8
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2024 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.io.IOException;
18 import java.net.URI;
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;
24 import java.util.Map;
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;
32
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;
99
100 import com.google.gson.Gson;
101 import com.google.gson.JsonSyntaxException;
102
103 /**
104  * The {@link NanoleafControllerHandler} is responsible for handling commands to the controller which
105  * affect all panels connected to it (e.g. selected effect)
106  *
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
110  */
111 @NonNullByDefault
112 public class NanoleafControllerHandler extends BaseBridgeHandler implements NanoleafControllerColorChangeListener {
113
114     // Pairing interval in seconds
115     private static final int PAIRING_INTERVAL = 10;
116     private static final int CONNECT_TIMEOUT = 10;
117
118     private final Logger logger = LoggerFactory.getLogger(NanoleafControllerHandler.class);
119     private final HttpClientFactory httpClientFactory;
120     private final HttpClient httpClient;
121
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;
129
130     private @NonNullByDefault({}) ScheduledFuture<?> pairingJob;
131     private @NonNullByDefault({}) ScheduledFuture<?> updateJob;
132     private @NonNullByDefault({}) ScheduledFuture<?> touchJob;
133     private final Gson gson = new Gson();
134
135     private @Nullable String address;
136     private int port;
137     private int refreshIntervall;
138     private @Nullable String authToken;
139     private @Nullable String deviceType;
140     private @NonNullByDefault({}) ControllerInfo controllerInfo;
141
142     private boolean touchJobRunning = false;
143
144     public NanoleafControllerHandler(Bridge bridge, HttpClientFactory httpClientFactory) {
145         super(bridge);
146         this.httpClientFactory = httpClientFactory;
147         this.httpClient = httpClientFactory.getCommonHttpClient();
148     }
149
150     private void initializeTouchHttpClient() {
151         String httpClientName = ThingWebClientUtil.buildWebClientConsumerName(thing.getUID(), null);
152
153         try {
154             httpClientSSETouchEvent = httpClientFactory.createHttpClient(httpClientName);
155             final HttpClient localHttpClientSSETouchEvent = this.httpClientSSETouchEvent;
156             if (localHttpClientSSETouchEvent != null) {
157                 localHttpClientSSETouchEvent.setConnectTimeout(CONNECT_TIMEOUT * 1000L);
158                 localHttpClientSSETouchEvent.start();
159             }
160         } catch (Exception e) {
161             logger.error(
162                     "Long running HttpClient for Nanoleaf controller handler {} cannot be started. Creating Handler failed.",
163                     httpClientName);
164             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, e.getMessage());
165         }
166
167         logger.debug("Using long SSE httpClient={} for {}}", httpClientSSETouchEvent, httpClientName);
168     }
169
170     @Override
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();
186         } else {
187             config.deviceType = DEVICE_TYPE_LIGHTPANELS;
188         }
189
190         setDeviceType(config.deviceType);
191         String propertyFirmwareVersion = properties.get(Thing.PROPERTY_FIRMWARE_VERSION);
192
193         try {
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");
201                     stopAllJobs();
202                 } else if (authToken != null && !authToken.isEmpty()) {
203                     stopPairingJob();
204                     startUpdateJob();
205                     startTouchJob();
206                 } else {
207                     logger.debug("No token found. Start pairing background job");
208                     updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
209                             "@text/error.nanoleaf.controller.noToken");
210                     startPairingJob();
211                     stopUpdateJob();
212                 }
213             } else {
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");
217                 stopAllJobs();
218             }
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");
224         }
225     }
226
227     @Override
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.");
232         } else {
233             try {
234                 if (command instanceof RefreshType) {
235                     updateFromControllerInfo();
236                 } else {
237                     switch (channelUID.getId()) {
238                         case CHANNEL_COLOR:
239                         case CHANNEL_COLOR_TEMPERATURE:
240                         case CHANNEL_COLOR_TEMPERATURE_ABS:
241                             sendStateCommand(channelUID.getId(), command);
242                             break;
243                         case CHANNEL_EFFECT:
244                             sendEffectCommand(command);
245                             break;
246                         case CHANNEL_RHYTHM_MODE:
247                             sendRhythmCommand(command);
248                             break;
249                         default:
250                             logger.warn("Channel with id {} not handled", channelUID.getId());
251                             break;
252                     }
253                 }
254             } catch (NanoleafUnauthorizedException nue) {
255                 logger.debug("Authorization for command {} to channelUID {} failed: {}", command, channelUID,
256                         nue.getMessage());
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");
263             }
264         }
265     }
266
267     @Override
268     public void handleRemoval() {
269         scheduler.execute(() -> {
270             try {
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());
277                     return;
278                 }
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());
284             }
285             stopAllJobs();
286             super.handleRemoval();
287             logger.debug("Nanoleaf controller removed");
288         });
289     }
290
291     @Override
292     public void dispose() {
293         stopAllJobs();
294         HttpClient localHttpClientSSETouchEvent = this.httpClientSSETouchEvent;
295         if (localHttpClientSSETouchEvent != null) {
296             try {
297                 localHttpClientSSETouchEvent.stop();
298             } catch (Exception e) {
299             }
300             this.httpClientSSETouchEvent = null;
301         }
302         super.dispose();
303         logger.debug("Disposing handler for Nanoleaf controller {}", getThing().getUID());
304     }
305
306     @Override
307     public Collection<Class<? extends ThingHandlerService>> getServices() {
308         return List.of(NanoleafPanelsDiscoveryService.class, NanoleafCommandDescriptionProvider.class);
309     }
310
311     public boolean registerControllerListener(NanoleafControllerListener controllerListener) {
312         logger.debug("Register new listener for controller {}", getThing().getUID());
313         return controllerListeners.add(controllerListener);
314     }
315
316     public boolean unregisterControllerListener(NanoleafControllerListener controllerListener) {
317         logger.debug("Unregister listener for controller {}", getThing().getUID());
318         return controllerListeners.remove(controllerListener);
319     }
320
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(), "");
328         return config;
329     }
330
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() : "";
337         }
338
339         return layoutView;
340     }
341
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);
346         }
347     }
348
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);
353             pairingJob = null;
354             logger.debug("Stopped pairing job");
355         }
356     }
357
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(),
364                         TimeUnit.SECONDS);
365             }
366         } else {
367             updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_PENDING,
368                     "@text/error.nanoleaf.controller.noToken");
369         }
370     }
371
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);
376             updateJob = null;
377             logger.debug("Stopped status job");
378         }
379     }
380
381     private synchronized void startTouchJob() {
382         NanoleafControllerConfig config = getConfigAs(NanoleafControllerConfig.class);
383         if (!config.deviceType.equals(DEVICE_TYPE_TOUCHSUPPORT)) {
384             logger.debug(
385                     "NOT starting TouchJob for Controller {} because it has wrong device type '{}' vs required '{}'",
386                     this.getThing().getUID(), config.deviceType, DEVICE_TYPE_TOUCHSUPPORT);
387         } else {
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());
395                 } else {
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);
400                 }
401             } else {
402                 logger.error("starting TouchJob for Controller {} failed - missing token", getThing().getUID());
403             }
404
405         }
406     }
407
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);
412
413             final Request localSSERequest = sseTouchjobRequest;
414             if (localSSERequest != null) {
415                 localSSERequest.abort(new NanoleafException("Touch detection stopped"));
416             }
417             if (!touchJob.isCancelled()) {
418                 touchJob.cancel(true);
419             }
420
421             touchJob = null;
422             touchJobRunning = false;
423             logger.debug("tj: touch job stopped for {} with client {}", thing.getUID(), httpClientSSETouchEvent);
424         }
425     }
426
427     private boolean hasTouchSupport(@Nullable String deviceType) {
428         return NanoleafBindingConstants.MODELS_WITH_TOUCHSUPPORT.contains(deviceType);
429     }
430
431     private void runUpdate() {
432         logger.debug("Run update job");
433
434         try {
435             updateFromControllerInfo();
436             startTouchJob();
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");
446             }
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");
454         }
455     }
456
457     private void runPairing() {
458         logger.debug("Run pairing job");
459
460         try {
461             final String localAuthToken = getAuthToken();
462             if (localAuthToken != null && !localAuthToken.isEmpty()) {
463                 if (pairingJob != null) {
464                     pairingJob.cancel(false);
465                 }
466
467                 logger.debug("Authentication token found. Canceling pairing job");
468                 return;
469             }
470
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);
477             }
478
479             if (authTokenResponse != null && authTokenResponse.getStatus() != HttpStatus.OK_200) {
480                 logger.debug("Pairing pending for {}. Controller returns status code {}", getThing().getUID(),
481                         authTokenResponse.getStatus());
482             } else {
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);
490                 }
491
492                 logger.debug("Pairing succeeded.");
493                 Configuration config = editConfiguration();
494
495                 config.put(NanoleafControllerConfig.AUTH_TOKEN, authTokenObject.getAuthToken());
496                 updateConfiguration(config);
497                 updateStatus(ThingStatus.ONLINE);
498                 // Update local field
499                 setAuthToken(authTokenObject.getAuthToken());
500
501                 stopPairingJob();
502                 startUpdateJob();
503                 startTouchJob();
504             }
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");
523         }
524     }
525
526     private synchronized void runTouchDetection() {
527         final HttpClient localhttpSSEClientTouchEvent = httpClientSSETouchEvent;
528         int eventHashcode = -1;
529         if (localhttpSSEClientTouchEvent != null) {
530             eventHashcode = localhttpSSEClientTouchEvent.hashCode();
531         }
532         if (touchJobRunning) {
533             logger.trace("tj: touch job {} touch job already running. quitting. {} controller {} with {}\",\n",
534                     touchJob, eventHashcode, thing.getUID(), httpClientSSETouchEvent);
535         } else {
536             try {
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();
547
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();
559
560                                         try {
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);
565                                         }
566                                     }
567                                 }
568                             }
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) -> {
576                             logger.trace(
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;
580                         });
581                     }
582                 }
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);
589             } finally {
590                 logger.trace("tj: touch job {} started for new request {} controller {} with {}\",\n",
591                         touchJob.hashCode(), eventHashcode, thing.getUID(), httpClientSSETouchEvent);
592             }
593
594         }
595     }
596
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());
604             } else {
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(),
609                                 event.getPanelId());
610                         if (panelHandler.getPanelID().equals(Integer.valueOf(event.getPanelId()))) {
611                             logger.debug("Panel {} found. Triggering item with gesture {}.", panelHandler.getPanelID(),
612                                     event.getGesture());
613                             panelHandler.updatePanelGesture(event.getGesture());
614                         }
615                     }
616
617                 });
618             }
619         });
620     }
621
622     /**
623      * Apply the swipe gesture to the controller
624      *
625      * @param gesture Only swipes are supported on the complete nanoleaf panels
626      */
627     private void updateControllerGesture(int gesture) {
628         switch (gesture) {
629             case 2:
630                 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_UP);
631                 break;
632             case 3:
633                 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_DOWN);
634                 break;
635             case 4:
636                 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_LEFT);
637                 break;
638             case 5:
639                 triggerChannel(CHANNEL_SWIPE, CHANNEL_SWIPE_EVENT_RIGHT);
640                 break;
641         }
642     }
643
644     private void updateFromControllerInfo() throws NanoleafException {
645         logger.debug("Update channels for controller {}", thing.getUID());
646         controllerInfo = receiveControllerInfo();
647         State state = controllerInfo.getState();
648
649         OnOffType powerState = state.getOnOff();
650
651         Ct colorTemperature = state.getColorTemperature();
652
653         float colorTempPercent = 0.0F;
654         int hue;
655         int saturation;
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();
664         }
665
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;
670
671         Sat stateSaturation = state.getSaturation();
672         saturation = stateSaturation != null ? stateSaturation.getValue() : 0;
673
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));
678
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()));
684
685         updatePanelColors();
686         if (EFFECT_NAME_SOLID_COLOR.equals(controllerInfo.getEffects().getSelect())) {
687             setSolidColor(stateColor);
688         }
689         updateProperties();
690         updateConfiguration();
691         updateLayout(controllerInfo.getPanelLayout());
692         updateVisualState(controllerInfo.getPanelLayout(), powerState);
693
694         for (NanoleafControllerListener controllerListener : controllerListeners) {
695             controllerListener.onControllerInfoFetched(getThing().getUID(), controllerInfo);
696         }
697     }
698
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();
703
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());
710                 }
711
712                 panelColors.setMultiple(allPanelIds, color);
713             } else {
714                 logger.debug("Missing position datum when setting solid color for {}", getThing().getUID());
715             }
716         } else {
717             logger.debug("Missing layout when setting solid color for {}", getThing().getUID());
718         }
719     }
720
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);
728             } else {
729                 config.put(NanoleafControllerConfig.DEVICE_TYPE, DEVICE_TYPE_LIGHTPANELS);
730                 logger.debug("Set to device type {}", DEVICE_TYPE_LIGHTPANELS);
731             }
732             updateConfiguration(config);
733             if (logger.isTraceEnabled()) {
734                 getConfig().getProperties().forEach((key, value) -> {
735                     logger.trace("Configuration property: key {} value {}", key, value);
736                 });
737             }
738         }
739     }
740
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);
752             });
753         }
754     }
755
756     private void updateVisualState(PanelLayout panelLayout, OnOffType powerState) {
757         ChannelUID stateChannel = new ChannelUID(getThing().getUID(), CHANNEL_VISUAL_STATE);
758
759         try {
760             PanelState panelState;
761             if (OnOffType.OFF.equals(powerState)) {
762                 // If powered off: show all panels as black
763                 panelState = new ConstantPanelState(HSBType.BLACK);
764             } else {
765                 // Static color for panels, use it
766                 panelState = new LivePanelState(panelColors);
767             }
768
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(),
774                         bytes.length);
775             } else {
776                 logger.debug("Visual state of {} failed to produce any image", getThing().getUID());
777             }
778         } catch (IOException ioex) {
779             logger.warn("Failed to create state image", ioex);
780         }
781     }
782
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
789                 return;
790             }
791         }
792
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());
796             return;
797         }
798
799         try {
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"));
804                 layoutImage = bytes;
805                 previousPanelLayout = panelLayout;
806                 logger.trace("Rendered layout of panel {} in updateState has {} bytes", getThing().getUID(),
807                         bytes.length);
808             } else {
809                 logger.debug("Layout of {} failed to produce any image", getThing().getUID());
810             }
811
812         } catch (IOException ioex) {
813             logger.warn("Failed to create layout image", ioex);
814         }
815     }
816
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);
822     }
823
824     private void sendStateCommand(String channel, Command command) throws NanoleafException {
825         State stateObject = new State();
826         switch (channel) {
827             case CHANNEL_COLOR:
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) {
853                         @Nullable
854                         Brightness brightness = controllerInfo.getState().getBrightness();
855                         int brightnessMin;
856                         int brightnessMax;
857                         if (brightness != null) {
858                             @Nullable
859                             Integer min = brightness.getMin();
860                             brightnessMin = (min == null) ? 0 : min;
861                             @Nullable
862                             Integer max = brightness.getMax();
863                             brightnessMax = (max == null) ? 0 : max;
864
865                             if (IncreaseDecreaseType.INCREASE.equals(command)) {
866                                 brightness.setValue(
867                                         Math.min(brightnessMax, brightness.getValue() + BRIGHTNESS_STEP_SIZE));
868                             } else {
869                                 brightness.setValue(
870                                         Math.max(brightnessMin, brightness.getValue() - BRIGHTNESS_STEP_SIZE));
871                             }
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);
876                         } else {
877                             logger.debug("Couldn't set brightness as it was null!");
878                         }
879                     }
880                 } else {
881                     logger.warn("Unhandled command {} with command type: {}", command, command.getClass().getName());
882                     return;
883                 }
884                 break;
885             case CHANNEL_COLOR_TEMPERATURE:
886                 if (command instanceof PercentType) {
887                     // Color temperature (percent)
888                     IntegerState state = new Ct();
889                     @Nullable
890                     Ct colorTemperature = controllerInfo.getState().getColorTemperature();
891
892                     int colorMin = 0;
893                     int colorMax = 0;
894                     if (colorTemperature != null) {
895                         @Nullable
896                         Integer min = colorTemperature.getMin();
897                         colorMin = (min == null) ? 0 : min;
898
899                         @Nullable
900                         Integer max = colorTemperature.getMax();
901                         colorMax = (max == null) ? 0 : max;
902                     }
903
904                     state.setValue(Math.round((colorMax - colorMin) * (100 - ((PercentType) command).intValue())
905                             / PercentType.HUNDRED.floatValue() + colorMin));
906                     stateObject.setState(state);
907                 } else {
908                     logger.warn("Unhandled command type: {}", command.getClass().getName());
909                     return;
910                 }
911                 break;
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);
921                         return;
922                     }
923                     state.setValue(tempKelvin.intValue());
924                 } else {
925                     logger.warn("Unhandled command type: {}", command.getClass().getName());
926                     return;
927                 }
928
929                 stateObject.setState(state);
930                 break;
931             default:
932                 logger.warn("Unhandled command type: {}", command.getClass().getName());
933                 return;
934         }
935
936         Request setNewStateRequest = OpenAPIUtils.requestBuilder(httpClient, getControllerConfig(), API_SET_VALUE,
937                 HttpMethod.PUT);
938         setNewStateRequest.content(new StringContentProvider(gson.toJson(stateObject)), "application/json");
939         OpenAPIUtils.sendOpenAPIRequest(setNewStateRequest);
940     }
941
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,
947                     HttpMethod.PUT);
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);
952         } else {
953             logger.warn("Unhandled command type: {}", command.getClass().getName());
954         }
955     }
956
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);
965         } else {
966             logger.warn("Unhandled command type: {}", command.getClass().getName());
967         }
968     }
969
970     private boolean hasStaticEffect() {
971         return EFFECT_NAME_STATIC_COLOR.equals(controllerInfo.getEffects().getSelect())
972                 || EFFECT_NAME_SOLID_COLOR.equals(controllerInfo.getEffects().getSelect());
973     }
974
975     /**
976      * Checks if we are in a mode where color changes should be rendered.
977      *
978      * @return True if a color change on a panel should be rendered
979      */
980     private boolean showsUpdatedColors() {
981         if (!hasStaticEffect()) {
982             logger.trace("Not updating colors as the device doesnt have a static/solid effect");
983             return false;
984         }
985
986         State state = controllerInfo.getState();
987         OnOffType powerState = state.getOnOff();
988         return OnOffType.ON.equals(powerState);
989     }
990
991     @Override
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());
996         } else {
997             logger.trace("Not updating colors. Update visual layout:  {}", updateVisualLayout);
998         }
999     }
1000
1001     /**
1002      * For individual panels to get access to the panel colors.
1003      *
1004      * @return Information about colors of panels.
1005      */
1006     public NanoleafPanelColors getColorInformation() {
1007         return panelColors;
1008     }
1009
1010     private void updatePanelColors() {
1011         // get panel color data from controller
1012         try {
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);
1018
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);
1024             // parse panel data
1025             parsePanelData(config, panelData);
1026
1027         } catch (NanoleafNotFoundException nfe) {
1028             logger.debug("Panel data could not be retrieved as no data was returned (static type missing?) : {}",
1029                     nfe.getMessage());
1030         } catch (NanoleafBadRequestException nfe) {
1031             logger.debug(
1032                     "Panel data could not be retrieved as request not expected(static type missing / dynamic type on) : {}",
1033                     nfe.getMessage());
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());
1038         }
1039     }
1040
1041     void parsePanelData(NanoleafControllerConfig config, ContentResponse panelData) {
1042         // panelData is in format (numPanels, (PanelId, 1, R, G, B, W, TransitionTime) * numPanel)
1043         @Nullable
1044         Write response = null;
1045
1046         String panelDataContent = panelData.getContentAsString();
1047         try {
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);
1052         }
1053
1054         if (response != null) {
1055             try {
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++) {
1063                         if (i % 7 == 0) {
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])));
1069                         }
1070                     }
1071                 } else {
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++) {
1076                         if (i % 8 == 0) {
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])));
1085                         }
1086                     }
1087                 }
1088             } finally {
1089                 updateVisualLayout = true;
1090                 onPanelChangedColor();
1091             }
1092         }
1093     }
1094
1095     private @Nullable String getAddress() {
1096         return address;
1097     }
1098
1099     private void setAddress(String address) {
1100         this.address = address;
1101     }
1102
1103     private int getPort() {
1104         return port;
1105     }
1106
1107     private void setPort(int port) {
1108         this.port = port;
1109     }
1110
1111     private int getRefreshInterval() {
1112         return refreshIntervall;
1113     }
1114
1115     private void setRefreshIntervall(int refreshIntervall) {
1116         this.refreshIntervall = refreshIntervall;
1117     }
1118
1119     @Nullable
1120     private String getAuthToken() {
1121         return authToken;
1122     }
1123
1124     private void setAuthToken(@Nullable String authToken) {
1125         this.authToken = authToken;
1126     }
1127
1128     @Nullable
1129     private String getDeviceType() {
1130         return deviceType;
1131     }
1132
1133     private void setDeviceType(String deviceType) {
1134         this.deviceType = deviceType;
1135     }
1136
1137     private void stopAllJobs() {
1138         stopPairingJob();
1139         stopUpdateJob();
1140         stopTouchJob();
1141     }
1142 }