2 * Copyright (c) 2010-2021 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.nanoleaf.internal.handler;
15 import static org.openhab.binding.nanoleaf.internal.NanoleafBindingConstants.*;
17 import java.math.BigDecimal;
18 import java.math.RoundingMode;
19 import java.util.Arrays;
20 import java.util.HashMap;
22 import java.util.concurrent.ScheduledFuture;
24 import org.eclipse.jdt.annotation.NonNullByDefault;
25 import org.eclipse.jdt.annotation.Nullable;
26 import org.eclipse.jetty.client.HttpClient;
27 import org.eclipse.jetty.client.api.ContentResponse;
28 import org.eclipse.jetty.client.api.Request;
29 import org.eclipse.jetty.client.util.StringContentProvider;
30 import org.eclipse.jetty.http.HttpMethod;
31 import org.openhab.binding.nanoleaf.internal.NanoleafBadRequestException;
32 import org.openhab.binding.nanoleaf.internal.NanoleafException;
33 import org.openhab.binding.nanoleaf.internal.NanoleafNotFoundException;
34 import org.openhab.binding.nanoleaf.internal.NanoleafUnauthorizedException;
35 import org.openhab.binding.nanoleaf.internal.OpenAPIUtils;
36 import org.openhab.binding.nanoleaf.internal.config.NanoleafControllerConfig;
37 import org.openhab.binding.nanoleaf.internal.model.Effects;
38 import org.openhab.binding.nanoleaf.internal.model.Write;
39 import org.openhab.core.io.net.http.HttpClientFactory;
40 import org.openhab.core.library.types.HSBType;
41 import org.openhab.core.library.types.IncreaseDecreaseType;
42 import org.openhab.core.library.types.OnOffType;
43 import org.openhab.core.library.types.PercentType;
44 import org.openhab.core.thing.Bridge;
45 import org.openhab.core.thing.ChannelUID;
46 import org.openhab.core.thing.CommonTriggerEvents;
47 import org.openhab.core.thing.Thing;
48 import org.openhab.core.thing.ThingStatus;
49 import org.openhab.core.thing.ThingStatusDetail;
50 import org.openhab.core.thing.ThingStatusInfo;
51 import org.openhab.core.thing.binding.BaseThingHandler;
52 import org.openhab.core.thing.binding.BridgeHandler;
53 import org.openhab.core.types.Command;
54 import org.openhab.core.types.RefreshType;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 import com.google.gson.Gson;
61 * The {@link NanoleafPanelHandler} is responsible for handling commands to the controller which
62 * affect an individual panels
64 * @author Martin Raepple - Initial contribution
65 * @author Stefan Höhn - Canvas Touch Support
68 public class NanoleafPanelHandler extends BaseThingHandler {
70 private static final PercentType MIN_PANEL_BRIGHTNESS = PercentType.ZERO;
71 private static final PercentType MAX_PANEL_BRIGHTNESS = PercentType.HUNDRED;
73 private final Logger logger = LoggerFactory.getLogger(NanoleafPanelHandler.class);
75 private HttpClient httpClient;
76 // JSON parser for API responses
77 private final Gson gson = new Gson();
79 // holds current color data per panel
80 private Map<String, HSBType> panelInfo = new HashMap<>();
82 private @NonNullByDefault({}) ScheduledFuture<?> singleTapJob;
83 private @NonNullByDefault({}) ScheduledFuture<?> doubleTapJob;
85 public NanoleafPanelHandler(Thing thing, HttpClientFactory httpClientFactory) {
87 this.httpClient = httpClientFactory.getCommonHttpClient();
91 public void initialize() {
92 logger.debug("Initializing handler for panel {}", getThing().getUID());
93 updateStatus(ThingStatus.OFFLINE);
94 Bridge controller = getBridge();
95 if (controller == null) {
96 initializePanel(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_UNINITIALIZED, ""));
97 } else if (ThingStatus.OFFLINE.equals(controller.getStatus())) {
98 initializePanel(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
99 "@text/error.nanoleaf.panel.controllerOffline"));
101 initializePanel(controller.getStatusInfo());
106 public void bridgeStatusChanged(ThingStatusInfo controllerStatusInfo) {
107 logger.debug("Controller status changed to {} -- {}", controllerStatusInfo,
108 controllerStatusInfo.getDescription() + "/" + controllerStatusInfo.getStatus() + "/"
109 + controllerStatusInfo.hashCode());
110 if (controllerStatusInfo.getStatus().equals(ThingStatus.OFFLINE)) {
111 initializePanel(new ThingStatusInfo(ThingStatus.OFFLINE, ThingStatusDetail.BRIDGE_OFFLINE,
112 "@text/error.nanoleaf.panel.controllerOffline"));
114 initializePanel(controllerStatusInfo);
119 public void handleCommand(ChannelUID channelUID, Command command) {
120 logger.debug("Received command {} for channel {}", command, channelUID);
122 switch (channelUID.getId()) {
123 case CHANNEL_PANEL_COLOR:
124 sendRenderedEffectCommand(command);
127 logger.warn("Channel with id {} not handled", channelUID.getId());
130 } catch (NanoleafUnauthorizedException nae) {
131 logger.warn("Authorization for command {} for channelUID {} failed: {}", command, channelUID,
133 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
134 "@text/error.nanoleaf.controller.invalidToken");
135 } catch (NanoleafException ne) {
136 logger.warn("Handling command {} for channelUID {} failed: {}", command, channelUID, ne.getMessage());
137 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
138 "@text/error.nanoleaf.controller.communication");
143 public void handleRemoval() {
144 logger.debug("Nanoleaf panel {} removed", getThing().getUID());
145 super.handleRemoval();
149 public void dispose() {
150 logger.debug("Disposing handler for Nanoleaf panel {}", getThing().getUID());
155 private void stopAllJobs() {
156 if (singleTapJob != null && !singleTapJob.isCancelled()) {
157 logger.debug("Stop single touch job");
158 singleTapJob.cancel(true);
159 this.singleTapJob = null;
161 if (doubleTapJob != null && !doubleTapJob.isCancelled()) {
162 logger.debug("Stop double touch job");
163 doubleTapJob.cancel(true);
164 this.doubleTapJob = null;
168 private void initializePanel(ThingStatusInfo panelStatus) {
169 updateStatus(panelStatus.getStatus(), panelStatus.getStatusDetail());
170 logger.debug("Panel {} status changed to {}-{}", this.getThing().getUID(), panelStatus.getStatus(),
171 panelStatus.getStatusDetail());
174 private void sendRenderedEffectCommand(Command command) throws NanoleafException {
175 logger.debug("Command Type: {}", command.getClass());
176 HSBType currentPanelColor = getPanelColor();
177 if (currentPanelColor != null) {
178 logger.debug("currentPanelColor: {}", currentPanelColor.toString());
180 HSBType newPanelColor = new HSBType();
182 if (command instanceof HSBType) {
183 newPanelColor = (HSBType) command;
184 } else if (command instanceof OnOffType && (currentPanelColor != null)) {
185 if (OnOffType.ON.equals(command)) {
186 newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
187 MAX_PANEL_BRIGHTNESS);
189 newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
190 MIN_PANEL_BRIGHTNESS);
192 } else if (command instanceof PercentType && (currentPanelColor != null)) {
193 PercentType brightness = new PercentType(
194 Math.max(MIN_PANEL_BRIGHTNESS.intValue(), ((PercentType) command).intValue()));
195 newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(), brightness);
196 } else if (command instanceof IncreaseDecreaseType && (currentPanelColor != null)) {
197 int brightness = currentPanelColor.getBrightness().intValue();
198 if (command.equals(IncreaseDecreaseType.INCREASE)) {
199 brightness = Math.min(MAX_PANEL_BRIGHTNESS.intValue(), brightness + BRIGHTNESS_STEP_SIZE);
201 brightness = Math.max(MIN_PANEL_BRIGHTNESS.intValue(), brightness - BRIGHTNESS_STEP_SIZE);
203 newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
204 new PercentType(brightness));
205 } else if (command instanceof RefreshType) {
206 logger.debug("Refresh command received");
209 logger.warn("Unhandled command type: {}", command.getClass().getName());
212 // store panel's new HSB value
213 logger.trace("Setting new color {}", newPanelColor);
214 panelInfo.put(getThing().getConfiguration().get(CONFIG_PANEL_ID).toString(), newPanelColor);
216 PercentType[] rgbPercent = newPanelColor.toRGB();
217 logger.trace("Setting new rgbpercent {} {} {}", rgbPercent[0], rgbPercent[1], rgbPercent[2]);
218 int red = rgbPercent[0].toBigDecimal().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
219 .multiply(new BigDecimal(255)).intValue();
220 int green = rgbPercent[1].toBigDecimal().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
221 .multiply(new BigDecimal(255)).intValue();
222 int blue = rgbPercent[2].toBigDecimal().divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP)
223 .multiply(new BigDecimal(255)).intValue();
224 logger.trace("Setting new rgb {} {} {}", red, green, blue);
225 Bridge bridge = getBridge();
226 if (bridge != null) {
227 Effects effects = new Effects();
228 Write write = new Write();
229 write.setCommand("display");
230 write.setAnimType("static");
231 String panelID = this.thing.getConfiguration().get(CONFIG_PANEL_ID).toString();
233 BridgeHandler handler = bridge.getHandler();
234 if (handler != null) {
235 NanoleafControllerConfig config = ((NanoleafControllerHandler) handler).getControllerConfig();
236 // Light Panels and Canvas use different stream commands
237 if (config.deviceType.equals(CONFIG_DEVICE_TYPE_LIGHTPANELS)
238 || config.deviceType.equals(CONFIG_DEVICE_TYPE_CANVAS)) {
239 logger.trace("Anim Data rgb {} {} {} {}", panelID, red, green, blue);
240 write.setAnimData(String.format("1 %s 1 %d %d %d 0 10", panelID, red, green, blue));
242 // this is only used in special streaming situations with canvas which is not yet supported
243 int quotient = Integer.divideUnsigned(Integer.valueOf(panelID), 256);
244 int remainder = Integer.remainderUnsigned(Integer.valueOf(panelID), 256);
246 String.format("0 1 %d %d %d %d %d 0 0 10", quotient, remainder, red, green, blue));
248 write.setLoop(false);
249 effects.setWrite(write);
250 Request setNewRenderedEffectRequest = OpenAPIUtils.requestBuilder(httpClient, config, API_EFFECT,
252 String content = gson.toJson(effects);
253 logger.debug("sending effect command from panel {}: {}", getThing().getUID(), content);
254 setNewRenderedEffectRequest.content(new StringContentProvider(content), "application/json");
255 OpenAPIUtils.sendOpenAPIRequest(setNewRenderedEffectRequest);
257 logger.warn("Couldn't set rendering effect as Bridge-Handler {} is null", bridge.getUID());
262 public void updatePanelColorChannel() {
264 HSBType panelColor = getPanelColor();
265 logger.trace("updatePanelColorChannel: panelColor: {}", panelColor);
266 if (panelColor != null) {
267 updateState(CHANNEL_PANEL_COLOR, panelColor);
272 * Apply the gesture to the panel
274 * @param gesture Only 0=single tap and 1=double tap are supported
276 public void updatePanelGesture(int gesture) {
279 triggerChannel(CHANNEL_PANEL_TAP, CommonTriggerEvents.SHORT_PRESSED);
282 triggerChannel(CHANNEL_PANEL_TAP, CommonTriggerEvents.DOUBLE_PRESSED);
287 public String getPanelID() {
288 String panelID = getThing().getConfiguration().get(CONFIG_PANEL_ID).toString();
292 private @Nullable HSBType getPanelColor() {
293 String panelID = getPanelID();
295 // get panel color data from controller
297 Effects effects = new Effects();
298 Write write = new Write();
299 write.setCommand("request");
300 write.setAnimName("*Static*");
301 effects.setWrite(write);
302 Bridge bridge = getBridge();
303 if (bridge != null) {
304 NanoleafControllerHandler handler = (NanoleafControllerHandler) bridge.getHandler();
305 if (handler != null) {
306 NanoleafControllerConfig config = handler.getControllerConfig();
307 logger.debug("Sending Request from Panel for getColor()");
308 Request setPanelUpdateRequest = OpenAPIUtils.requestBuilder(httpClient, config, API_EFFECT,
310 setPanelUpdateRequest.content(new StringContentProvider(gson.toJson(effects)), "application/json");
311 ContentResponse panelData = OpenAPIUtils.sendOpenAPIRequest(setPanelUpdateRequest);
314 parsePanelData(panelID, config, panelData);
317 } catch (NanoleafNotFoundException nfe) {
318 logger.debug("Panel data could not be retrieved as no data was returned (static type missing?) : {}",
320 } catch (NanoleafBadRequestException nfe) {
322 "Panel data could not be retrieved as request not expected(static type missing / dynamic type on) : {}",
324 } catch (NanoleafException nue) {
325 updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR,
326 "@text/error.nanoleaf.panel.communication");
327 logger.debug("Panel data could not be retrieved: {}", nue.getMessage());
330 return panelInfo.get(panelID);
333 void parsePanelData(String panelID, NanoleafControllerConfig config, ContentResponse panelData) {
334 // panelData is in format (numPanels, (PanelId, 1, R, G, B, W, TransitionTime) * numPanel)
336 Write response = gson.fromJson(panelData.getContentAsString(), Write.class);
337 if (response != null) {
338 String[] tokenizedData = response.getAnimData().split(" ");
339 if (config.deviceType.equals(CONFIG_DEVICE_TYPE_LIGHTPANELS)
340 || config.deviceType.equals(CONFIG_DEVICE_TYPE_CANVAS)) {
341 // panelData is in format (numPanels (PanelId 1 R G B W TransitionTime) * numPanel)
342 String[] panelDataPoints = Arrays.copyOfRange(tokenizedData, 1, tokenizedData.length);
343 for (int i = 0; i < panelDataPoints.length; i++) {
345 String id = panelDataPoints[i];
346 if (id.equals(panelID)) {
347 // found panel data - store it
348 panelInfo.put(panelID,
349 HSBType.fromRGB(Integer.parseInt(panelDataPoints[i + 2]),
350 Integer.parseInt(panelDataPoints[i + 3]),
351 Integer.parseInt(panelDataPoints[i + 4])));
356 // panelData is in format (0 numPanels (quotient(panelID) remainder(panelID) R G B W 0
357 // quotient(TransitionTime) remainder(TransitionTime)) * numPanel)
358 String[] panelDataPoints = Arrays.copyOfRange(tokenizedData, 2, tokenizedData.length);
359 for (int i = 0; i < panelDataPoints.length; i++) {
361 String idQuotient = panelDataPoints[i];
362 String idRemainder = panelDataPoints[i + 1];
363 Integer idNum = Integer.valueOf(idQuotient) * 256 + Integer.valueOf(idRemainder);
364 if (String.valueOf(idNum).equals(panelID)) {
365 // found panel data - store it
366 panelInfo.put(panelID,
367 HSBType.fromRGB(Integer.parseInt(panelDataPoints[i + 3]),
368 Integer.parseInt(panelDataPoints[i + 4]),
369 Integer.parseInt(panelDataPoints[i + 5])));