]> git.basschouten.com Git - openhab-addons.git/blob
020f55f57b7b2bd472c8719f4dd359ee2415069b
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2021 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.math.BigDecimal;
18 import java.math.RoundingMode;
19 import java.util.Arrays;
20 import java.util.HashMap;
21 import java.util.Map;
22 import java.util.concurrent.ScheduledFuture;
23
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;
57
58 import com.google.gson.Gson;
59
60 /**
61  * The {@link NanoleafPanelHandler} is responsible for handling commands to the controller which
62  * affect an individual panels
63  *
64  * @author Martin Raepple - Initial contribution
65  * @author Stefan Höhn - Canvas Touch Support
66  */
67 @NonNullByDefault
68 public class NanoleafPanelHandler extends BaseThingHandler {
69
70     private static final PercentType MIN_PANEL_BRIGHTNESS = PercentType.ZERO;
71     private static final PercentType MAX_PANEL_BRIGHTNESS = PercentType.HUNDRED;
72
73     private final Logger logger = LoggerFactory.getLogger(NanoleafPanelHandler.class);
74
75     private HttpClient httpClient;
76     // JSON parser for API responses
77     private final Gson gson = new Gson();
78
79     // holds current color data per panel
80     private Map<String, HSBType> panelInfo = new HashMap<>();
81
82     private @NonNullByDefault({}) ScheduledFuture<?> singleTapJob;
83     private @NonNullByDefault({}) ScheduledFuture<?> doubleTapJob;
84
85     public NanoleafPanelHandler(Thing thing, HttpClientFactory httpClientFactory) {
86         super(thing);
87         this.httpClient = httpClientFactory.getCommonHttpClient();
88     }
89
90     @Override
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"));
100         } else {
101             initializePanel(controller.getStatusInfo());
102         }
103     }
104
105     @Override
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"));
113         } else {
114             initializePanel(controllerStatusInfo);
115         }
116     }
117
118     @Override
119     public void handleCommand(ChannelUID channelUID, Command command) {
120         logger.debug("Received command {} for channel {}", command, channelUID);
121         try {
122             switch (channelUID.getId()) {
123                 case CHANNEL_PANEL_COLOR:
124                     sendRenderedEffectCommand(command);
125                     break;
126                 default:
127                     logger.warn("Channel with id {} not handled", channelUID.getId());
128                     break;
129             }
130         } catch (NanoleafUnauthorizedException nae) {
131             logger.warn("Authorization for command {} for channelUID {} failed: {}", command, channelUID,
132                     nae.getMessage());
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");
139         }
140     }
141
142     @Override
143     public void handleRemoval() {
144         logger.debug("Nanoleaf panel {} removed", getThing().getUID());
145         super.handleRemoval();
146     }
147
148     @Override
149     public void dispose() {
150         logger.debug("Disposing handler for Nanoleaf panel {}", getThing().getUID());
151         stopAllJobs();
152         super.dispose();
153     }
154
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;
160         }
161         if (doubleTapJob != null && !doubleTapJob.isCancelled()) {
162             logger.debug("Stop double touch job");
163             doubleTapJob.cancel(true);
164             this.doubleTapJob = null;
165         }
166     }
167
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());
172     }
173
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());
179         }
180         HSBType newPanelColor = new HSBType();
181
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);
188             } else {
189                 newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
190                         MIN_PANEL_BRIGHTNESS);
191             }
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);
200             } else {
201                 brightness = Math.max(MIN_PANEL_BRIGHTNESS.intValue(), brightness - BRIGHTNESS_STEP_SIZE);
202             }
203             newPanelColor = new HSBType(currentPanelColor.getHue(), currentPanelColor.getSaturation(),
204                     new PercentType(brightness));
205         } else if (command instanceof RefreshType) {
206             logger.debug("Refresh command received");
207             return;
208         } else {
209             logger.warn("Unhandled command type: {}", command.getClass().getName());
210             return;
211         }
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);
215         // transform to RGB
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();
232             @Nullable
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));
241                 } else {
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);
245                     write.setAnimData(
246                             String.format("0 1 %d %d %d %d %d 0 0 10", quotient, remainder, red, green, blue));
247                 }
248                 write.setLoop(false);
249                 effects.setWrite(write);
250                 Request setNewRenderedEffectRequest = OpenAPIUtils.requestBuilder(httpClient, config, API_EFFECT,
251                         HttpMethod.PUT);
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);
256             } else {
257                 logger.warn("Couldn't set rendering effect as Bridge-Handler {} is null", bridge.getUID());
258             }
259         }
260     }
261
262     public void updatePanelColorChannel() {
263         @Nullable
264         HSBType panelColor = getPanelColor();
265         logger.trace("updatePanelColorChannel: panelColor: {}", panelColor);
266         if (panelColor != null) {
267             updateState(CHANNEL_PANEL_COLOR, panelColor);
268         }
269     }
270
271     /**
272      * Apply the gesture to the panel
273      *
274      * @param gesture Only 0=single tap and 1=double tap are supported
275      */
276     public void updatePanelGesture(int gesture) {
277         switch (gesture) {
278             case 0:
279                 triggerChannel(CHANNEL_PANEL_TAP, CommonTriggerEvents.SHORT_PRESSED);
280                 break;
281             case 1:
282                 triggerChannel(CHANNEL_PANEL_TAP, CommonTriggerEvents.DOUBLE_PRESSED);
283                 break;
284         }
285     }
286
287     public String getPanelID() {
288         String panelID = getThing().getConfiguration().get(CONFIG_PANEL_ID).toString();
289         return panelID;
290     }
291
292     private @Nullable HSBType getPanelColor() {
293         String panelID = getPanelID();
294
295         // get panel color data from controller
296         try {
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,
309                             HttpMethod.PUT);
310                     setPanelUpdateRequest.content(new StringContentProvider(gson.toJson(effects)), "application/json");
311                     ContentResponse panelData = OpenAPIUtils.sendOpenAPIRequest(setPanelUpdateRequest);
312                     // parse panel data
313
314                     parsePanelData(panelID, config, panelData);
315                 }
316             }
317         } catch (NanoleafNotFoundException nfe) {
318             logger.debug("Panel data could not be retrieved as no data was returned (static type missing?) : {}",
319                     nfe.getMessage());
320         } catch (NanoleafBadRequestException nfe) {
321             logger.debug(
322                     "Panel data could not be retrieved as request not expected(static type missing / dynamic type on) : {}",
323                     nfe.getMessage());
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());
328         }
329
330         return panelInfo.get(panelID);
331     }
332
333     void parsePanelData(String panelID, NanoleafControllerConfig config, ContentResponse panelData) {
334         // panelData is in format (numPanels, (PanelId, 1, R, G, B, W, TransitionTime) * numPanel)
335         @Nullable
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++) {
344                     if (i % 7 == 0) {
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])));
352                         }
353                     }
354                 }
355             } else {
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++) {
360                     if (i % 8 == 0) {
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])));
370                         }
371                     }
372                 }
373             }
374         }
375     }
376 }