]> git.basschouten.com Git - openhab-addons.git/blob
8fc49526f68b033fcc549cbae14d5b85a2de30a4
[openhab-addons.git] /
1 /**
2  * Copyright (c) 2010-2023 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.shelly.internal.handler;
14
15 import static org.openhab.binding.shelly.internal.ShellyBindingConstants.*;
16 import static org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.*;
17 import static org.openhab.binding.shelly.internal.util.ShellyUtils.*;
18
19 import java.util.Map;
20 import java.util.TreeMap;
21
22 import org.eclipse.jdt.annotation.NonNullByDefault;
23 import org.eclipse.jetty.client.HttpClient;
24 import org.openhab.binding.shelly.internal.api.ShellyApiException;
25 import org.openhab.binding.shelly.internal.api.ShellyDeviceProfile;
26 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsRgbwLight;
27 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellySettingsStatus;
28 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyShortLightStatus;
29 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusLight;
30 import org.openhab.binding.shelly.internal.api1.Shelly1ApiJsonDTO.ShellyStatusLightChannel;
31 import org.openhab.binding.shelly.internal.api1.Shelly1CoapServer;
32 import org.openhab.binding.shelly.internal.config.ShellyBindingConfiguration;
33 import org.openhab.binding.shelly.internal.provider.ShellyChannelDefinitions;
34 import org.openhab.binding.shelly.internal.provider.ShellyTranslationProvider;
35 import org.openhab.core.library.types.DecimalType;
36 import org.openhab.core.library.types.HSBType;
37 import org.openhab.core.library.types.IncreaseDecreaseType;
38 import org.openhab.core.library.types.OnOffType;
39 import org.openhab.core.library.types.PercentType;
40 import org.openhab.core.library.types.StringType;
41 import org.openhab.core.library.unit.Units;
42 import org.openhab.core.thing.ChannelUID;
43 import org.openhab.core.thing.Thing;
44 import org.openhab.core.types.Command;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 /**
49  * The {@link ShellyLightHandler} handles light (Bulb, Duo and RGBW2) specific commands and status. All other commands
50  * will be routet of the ShellyBaseHandler.
51  *
52  * @author Markus Michels - Initial contribution
53  */
54 @NonNullByDefault
55 public class ShellyLightHandler extends ShellyBaseHandler {
56     private final Logger logger = LoggerFactory.getLogger(ShellyLightHandler.class);
57     private final Map<Integer, ShellyColorUtils> channelColors;
58
59     public ShellyLightHandler(final Thing thing, final ShellyTranslationProvider translationProvider,
60             final ShellyBindingConfiguration bindingConfig, final ShellyThingTable thingTable,
61             final Shelly1CoapServer coapServer, final HttpClient httpClient) {
62         super(thing, translationProvider, bindingConfig, thingTable, coapServer, httpClient);
63         channelColors = new TreeMap<>();
64     }
65
66     @Override
67     public void initialize() {
68         logger.debug("Thing is using  {}", this.getClass());
69         super.initialize();
70     }
71
72     @Override
73     public boolean handleDeviceCommand(ChannelUID channelUID, Command command) throws IllegalArgumentException {
74         String groupName = getString(channelUID.getGroupId());
75         if (groupName.isEmpty()) {
76             throw new IllegalArgumentException("Empty groupName");
77         }
78
79         int lightId = getLightIdFromGroup(groupName);
80         logger.trace("{}: Execute command {} on channel {}, lightId={}", thingName, command, channelUID.getAsString(),
81                 lightId);
82
83         try {
84             ShellyColorUtils oldCol = getCurrentColors(lightId);
85             oldCol.mode = profile.mode;
86             ShellyColorUtils col = new ShellyColorUtils(oldCol);
87
88             boolean update = true;
89             switch (channelUID.getIdWithoutGroup()) {
90                 default: // non-bulb commands will be handled by the generic handler
91                     return false;
92
93                 case CHANNEL_LIGHT_POWER:
94                     logger.debug("{}: Switch light {}", thingName, command);
95                     api.setLightParm(lightId, SHELLY_LIGHT_TURN,
96                             command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
97                     col.power = (OnOffType) command;
98                     requestUpdates(1, false);
99                     update = false;
100                     break;
101                 case CHANNEL_LIGHT_COLOR_MODE:
102                     logger.debug("{}: Select color mode {}", thingName, command);
103                     col.setMode((OnOffType) command == OnOffType.ON ? SHELLY_MODE_COLOR : SHELLY_MODE_WHITE);
104                     break;
105                 case CHANNEL_COLOR_PICKER:
106                     logger.debug("{}: Update colors from color picker", thingName);
107                     update = handleColorPicker(profile, lightId, col, command);
108                     break;
109                 case CHANNEL_COLOR_FULL:
110                     logger.debug("{}: Set colors to {}", thingName, command);
111                     handleFullColor(col, command);
112                     break;
113                 case CHANNEL_COLOR_RED:
114                     col.setRed(setColor(lightId, SHELLY_COLOR_RED, command, SHELLY_MAX_COLOR));
115                     break;
116                 case CHANNEL_COLOR_GREEN:
117                     col.setGreen(setColor(lightId, SHELLY_COLOR_GREEN, command, SHELLY_MAX_COLOR));
118                     break;
119                 case CHANNEL_COLOR_BLUE:
120                     col.setBlue(setColor(lightId, SHELLY_COLOR_BLUE, command, SHELLY_MAX_COLOR));
121                     break;
122                 case CHANNEL_COLOR_WHITE:
123                     col.setWhite(setColor(lightId, SHELLY_COLOR_WHITE, command, SHELLY_MAX_COLOR));
124                     break;
125                 case CHANNEL_COLOR_GAIN:
126                     col.setGain(setColor(lightId, SHELLY_COLOR_GAIN, command, SHELLY_MIN_GAIN, SHELLY_MAX_GAIN));
127                     break;
128                 case CHANNEL_BRIGHTNESS: // only in white mode
129                     if (profile.inColor && !profile.isBulb) {
130                         logger.debug("{}: Not in white mode, brightness not available", thingName);
131                         break;
132                     }
133
134                     int value = -1;
135                     if (command instanceof OnOffType) { // Switch
136                         logger.debug("{}: Switch light {}", thingName, command);
137                         ShellyShortLightStatus light = api.setLightTurn(lightId,
138                                 command == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
139                         col.power = getOnOff(light.ison);
140                         col.setBrightness(light.brightness);
141                         updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Switch", col.power);
142                         updateChannel(CHANNEL_COLOR_WHITE, CHANNEL_BRIGHTNESS + "$Value", toQuantityType(
143                                 (double) (col.power == OnOffType.ON ? col.brightness : 0), DIGITS_NONE, Units.PERCENT));
144                         update = false;
145                         break;
146                     }
147
148                     if (command instanceof PercentType percentCommand) {
149                         Float percent = percentCommand.floatValue();
150                         value = percent.intValue(); // 0..100% = 0..100
151                         logger.debug("{}: Set brightness to {}%/{}", thingName, percent, value);
152                     } else if (command instanceof DecimalType decimalCommand) {
153                         value = decimalCommand.intValue();
154                         logger.debug("{}: Set brightness to {} (Integer)", thingName, value);
155                     }
156                     if (value == 0) {
157                         logger.debug("{}: Brightness=0 -> switch light OFF", thingName);
158                         api.setLightTurn(lightId, SHELLY_API_OFF);
159                         update = false;
160                     } else {
161                         if (command instanceof IncreaseDecreaseType increaseDecreaseCommand) {
162                             ShellyShortLightStatus light = api.getLightStatus(lightId);
163                             if (increaseDecreaseCommand.equals(IncreaseDecreaseType.INCREASE)) {
164                                 value = Math.min(light.brightness + DIM_STEPSIZE, 100);
165                             } else {
166                                 value = Math.max(light.brightness - DIM_STEPSIZE, 0);
167                             }
168                             logger.trace("{}: Change brightness from {} to {}", thingName, light.brightness, value);
169                         }
170
171                         validateRange("brightness", value, 0, 100);
172                         logger.debug("{}: Changing brightness from {} to {}", thingName, oldCol.brightness, value);
173                         col.setBrightness(value);
174                     }
175                     updateChannel(CHANNEL_GROUP_LIGHT_CONTROL, CHANNEL_LIGHT_POWER,
176                             value > 0 ? OnOffType.ON : OnOffType.OFF);
177                     break;
178
179                 case CHANNEL_COLOR_TEMP:
180                     Integer temp = -1;
181                     if (command instanceof PercentType percentCommand) {
182                         logger.debug("{}: Set color temp to {}%", thingName, percentCommand.floatValue());
183                         Float percent = percentCommand.floatValue() / 100;
184                         temp = new DecimalType(col.minTemp + ((col.maxTemp - col.minTemp)) * percent).intValue();
185                         logger.debug("{}: Converted color-temp {}% to {}K (from Percent to Integer)", thingName,
186                                 percent, temp);
187                     } else if (command instanceof DecimalType decimalCommand) {
188                         temp = decimalCommand.intValue();
189                         logger.debug("{}: Set color temp to {}K (Integer)", thingName, temp);
190                     }
191                     validateRange(CHANNEL_COLOR_TEMP, temp, col.minTemp, col.maxTemp);
192                     col.setTemp(temp);
193                     col.brightness = -1;
194                     break;
195
196                 case CHANNEL_COLOR_EFFECT:
197                     Integer effect = ((DecimalType) command).intValue();
198                     logger.debug("{}: Set color effect to {}", thingName, effect);
199                     validateRange("effect", effect, SHELLY_MIN_EFFECT, SHELLY_MAX_EFFECT);
200                     col.setEffect(effect.intValue());
201             }
202
203             if (update) {
204                 // check for switching color mode
205                 if (profile.isBulb && !col.mode.isEmpty() && !col.mode.equals(oldCol.mode)) {
206                     logger.debug("{}: Color mode changed from {} to {}, set new mode", thingName, oldCol.mode,
207                             col.mode);
208                     api.setLightMode(col.mode);
209                 }
210
211                 // send changed colors to the device
212                 sendColors(profile, lightId, oldCol, col, config.brightnessAutoOn);
213             }
214             return true;
215         } catch (ShellyApiException e) {
216             logger.debug("{}: Unable to handle command: {}", thingName, e.toString());
217             return false;
218         } catch (IllegalArgumentException e) {
219             logger.debug("{}: Unable to handle command", thingName, e);
220             return false;
221         }
222     }
223
224     @SuppressWarnings("deprecation")
225     private boolean handleColorPicker(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils col,
226             Command command) throws ShellyApiException {
227         boolean updated = false;
228         if (command instanceof HSBType hsb) {
229             logger.debug("HSB-Info={}, Hue={}, getRGB={}, toRGB={}/{}/{}", hsb, hsb.getHue(),
230                     String.format("0x%08X", hsb.getRGB()), hsb.toRGB()[0], hsb.toRGB()[1], hsb.toRGB()[2]);
231             if (hsb.toString().contains("360,")) {
232                 logger.trace("{}: need to fix the Hue value (360->0)", thingName);
233                 HSBType fixHue = new HSBType(new DecimalType(0), hsb.getSaturation(), hsb.getBrightness());
234                 hsb = fixHue;
235             }
236
237             col.setRed(getColorFromHSB(hsb.getRed()));
238             col.setBlue(getColorFromHSB(hsb.getBlue()));
239             col.setGreen(getColorFromHSB(hsb.getGreen()));
240             col.setBrightness(getColorFromHSB(hsb.getBrightness(), BRIGHTNESS_FACTOR));
241             // white, gain and temp are not part of the HSB color scheme
242             updated = true;
243         } else if (command instanceof PercentType percentCommand) {
244             if (!profile.inColor || profile.isBulb) {
245                 col.brightness = SHELLY_MAX_BRIGHTNESS * percentCommand.intValue();
246                 updated = true;
247             }
248         } else if (command instanceof OnOffType onOffCommand) {
249             logger.debug("{}: Switch light {}", thingName, onOffCommand);
250             api.setLightParm(lightId, SHELLY_LIGHT_TURN, onOffCommand == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
251             col.power = onOffCommand;
252         } else if (command instanceof IncreaseDecreaseType) {
253             if (!profile.inColor || profile.isBulb) {
254                 logger.debug("{}: {} brightness by {}", thingName, command, SHELLY_DIM_STEPSIZE);
255                 PercentType percent = (PercentType) super.getChannelValue(CHANNEL_GROUP_COLOR_CONTROL,
256                         CHANNEL_BRIGHTNESS);
257                 int currentBrightness = percent.intValue() * SHELLY_MAX_BRIGHTNESS;
258                 int newBrightness = currentBrightness;
259                 if (command == IncreaseDecreaseType.DECREASE) {
260                     newBrightness = Math.max(currentBrightness - SHELLY_DIM_STEPSIZE, 0);
261                 } else {
262                     newBrightness = Math.min(currentBrightness + SHELLY_DIM_STEPSIZE, SHELLY_MAX_BRIGHTNESS);
263                 }
264                 col.brightness = newBrightness;
265                 updated = currentBrightness != newBrightness;
266             }
267         }
268         return updated;
269     }
270
271     private boolean handleFullColor(ShellyColorUtils col, Command command) throws IllegalArgumentException {
272         String color = command.toString().toLowerCase();
273         if (color.contains(",")) {
274             col.fromRGBW(color);
275         } else if (color.equals(SHELLY_COLOR_RED)) {
276             col.setRGBW(SHELLY_MAX_COLOR, 0, 0, 0);
277         } else if (color.equals(SHELLY_COLOR_GREEN)) {
278             col.setRGBW(0, SHELLY_MAX_COLOR, 0, 0);
279         } else if (color.equals(SHELLY_COLOR_BLUE)) {
280             col.setRGBW(0, 0, SHELLY_MAX_COLOR, 0);
281         } else if (color.equals(SHELLY_COLOR_YELLOW)) {
282             col.setRGBW(SHELLY_MAX_COLOR, SHELLY_MAX_COLOR, 0, 0);
283         } else if (color.equals(SHELLY_COLOR_WHITE)) {
284             col.setRGBW(0, 0, 0, SHELLY_MAX_COLOR);
285             col.setMode(SHELLY_MODE_WHITE);
286         } else {
287             throw new IllegalArgumentException("Invalid full color selection: " + color);
288         }
289         col.setMode(color.equals(SHELLY_MODE_WHITE) ? SHELLY_MODE_WHITE : SHELLY_MODE_COLOR);
290         return true;
291     }
292
293     private ShellyColorUtils getCurrentColors(int lightId) {
294         ShellyColorUtils col = channelColors.get(lightId);
295         if (col == null) {
296             col = new ShellyColorUtils(); // create a new entry
297             col.setMinMaxTemp(profile.minTemp, profile.maxTemp);
298             channelColors.put(lightId, col);
299             logger.trace("{}: Colors entry created for lightId {}", thingName, lightId);
300         } else {
301             logger.trace(
302                     "{}: Colors loaded for lightId {}: power={}, RGBW={}/{}/{}/{}, gain={}, brightness={}, color temp={} (min={}, max={}",
303                     thingName, lightId, col.power, col.red, col.green, col.blue, col.white, col.gain, col.brightness,
304                     col.temp, col.minTemp, col.maxTemp);
305         }
306         return col;
307     }
308
309     @Override
310     public boolean updateDeviceStatus(ShellySettingsStatus genericStatus) throws ShellyApiException {
311         if (!profile.isInitialized()) {
312             logger.debug("{}: Device not yet initialized!", thingName);
313             return false;
314         }
315         if (!profile.isLight) {
316             logger.debug("{}: ERROR: Device is not a light. but class ShellyHandlerLight is called!", thingName);
317         }
318
319         ShellyStatusLight status = api.getLightStatus();
320         logger.trace("{}: Updating light status in {} mode, {} channel(s)", thingName, profile.mode,
321                 status.lights.size());
322
323         // In white mode we have multiple channels
324         int lightId = 0;
325         boolean updated = false;
326         for (ShellyStatusLightChannel light : status.lights) {
327             Integer channelId = lightId + 1;
328             String controlGroup = buildControlGroupName(profile, channelId);
329             createLightChannels(light, lightId);
330             // The bulb has a combined channel set for color or white mode
331             // The RGBW2 uses 2 different thing types: color=1 channel, white=4 channel
332             if (profile.isBulb) {
333                 updateChannel(CHANNEL_GROUP_LIGHT_CONTROL, CHANNEL_LIGHT_COLOR_MODE, getOnOff(profile.inColor));
334             }
335
336             ShellyColorUtils col = getCurrentColors(lightId);
337             col.power = getOnOff(light.ison);
338
339             if (profile.settings.lights != null) {
340                 // Channel control/timer
341                 ShellySettingsRgbwLight ls = profile.settings.lights.get(lightId);
342                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_AUTOON,
343                         toQuantityType(getDouble(ls.autoOn), Units.SECOND));
344                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_AUTOOFF,
345                         toQuantityType(getDouble(ls.autoOff), Units.SECOND));
346                 updated |= updateChannel(controlGroup, CHANNEL_LIGHT_POWER, col.power);
347                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_ACTIVE, getOnOff(light.hasTimer));
348                 updated |= updateChannel(controlGroup, CHANNEL_LIGHT_POWER, col.power);
349             }
350
351             if (getBool(light.overpower)) {
352                 postEvent(ALARM_TYPE_OVERPOWER, false);
353             }
354
355             if (profile.inColor) {
356                 logger.trace("{}: update color settings", thingName);
357                 col.setRGBW(getInteger(light.red), getInteger(light.green), getInteger(light.blue),
358                         getInteger(light.white));
359                 col.setGain(getInteger(light.gain));
360                 col.setEffect(getInteger(light.effect));
361
362                 String colorGroup = CHANNEL_GROUP_COLOR_CONTROL;
363                 logger.trace("{}: Update channels for group {}: RGBW={}/{}/{}, in %:{}%/{}%/{}%, white={}%, gain={}%",
364                         thingName, colorGroup, col.red, col.green, col.blue, col.percentRed, col.percentGreen,
365                         col.percentBlue, col.percentWhite, col.percentGain);
366                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_RED, col.percentRed);
367                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_GREEN, col.percentGreen);
368                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_BLUE, col.percentBlue);
369                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_WHITE, col.percentWhite);
370                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_GAIN, col.percentGain);
371                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_EFFECT, getDecimal(col.effect));
372                 setFullColor(colorGroup, col);
373
374                 logger.trace("{}: update {}.color picker", thingName, colorGroup);
375                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_PICKER, col.toHSB());
376             }
377
378             if (!profile.inColor || profile.isBulb) {
379                 String whiteGroup = buildWhiteGroupName(profile, channelId);
380                 col.setBrightness(getInteger(light.brightness));
381                 updated |= updateChannel(whiteGroup, CHANNEL_BRIGHTNESS + "$Switch", col.power);
382                 updated |= updateChannel(whiteGroup, CHANNEL_BRIGHTNESS + "$Value",
383                         toQuantityType(col.power == OnOffType.ON ? col.percentBrightness.doubleValue() : 0, DIGITS_NONE,
384                                 Units.PERCENT));
385
386                 if ((profile.isBulb || profile.isDuo) && (light.temp != null)) {
387                     col.setTemp(getInteger(light.temp));
388                     updated |= updateChannel(whiteGroup, CHANNEL_COLOR_TEMP, col.percentTemp);
389                     logger.trace("{}: update {}.color picker", thingName, whiteGroup);
390                     updated |= updateChannel(whiteGroup, CHANNEL_COLOR_PICKER, col.toHSB());
391                 }
392             }
393
394             // continue with next light
395             lightId++;
396         }
397         return updated;
398     }
399
400     private void createLightChannels(ShellyStatusLightChannel status, int idx) {
401         if (!areChannelsCreated()) {
402             updateChannelDefinitions(ShellyChannelDefinitions.createLightChannels(getThing(), profile, status, idx));
403         }
404     }
405
406     private Integer setColor(Integer lightId, String colorName, Command command, Integer minValue, Integer maxValue)
407             throws ShellyApiException, IllegalArgumentException {
408         Integer value = -1;
409         logger.debug("{}: Set {} to {} ({})", thingName, colorName, command, command.getClass());
410         if (command instanceof PercentType percentCommand) {
411             double v = (double) maxValue * percentCommand.doubleValue() / 100.0;
412             value = (int) v;
413             logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percentCommand, value);
414         } else if (command instanceof DecimalType decimalCommand) {
415             value = decimalCommand.intValue();
416             logger.debug("Value for {} is a number: {}", colorName, value);
417         } else if (command instanceof OnOffType onOffCommand) {
418             value = onOffCommand.equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR;
419             logger.debug("{}: Value for {} of type OnOff was converted to {}", thingName, colorName, value);
420         } else {
421             throw new IllegalArgumentException(
422                     "Invalid value type for " + colorName + ": " + value + " / type " + value.getClass());
423         }
424         validateRange(colorName, value, minValue, maxValue);
425         return value.intValue();
426     }
427
428     private Integer setColor(Integer lightId, String colorName, Command command, Integer maxValue)
429             throws ShellyApiException, IllegalArgumentException {
430         return setColor(lightId, colorName, command, 0, maxValue);
431     }
432
433     private void setFullColor(String colorGroup, ShellyColorUtils col) {
434         if ((col.red == SHELLY_MAX_COLOR) && (col.green == SHELLY_MAX_COLOR) && (col.blue == 0)) {
435             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_YELLOW));
436         } else if ((col.red == SHELLY_MAX_COLOR) && (col.green == 0) && (col.blue == 0)) {
437             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_RED));
438         } else if ((col.red == 0) && (col.green == SHELLY_MAX_COLOR) && (col.blue == 0)) {
439             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_GREEN));
440         } else if ((col.red == 0) && (col.green == 0) && (col.blue == SHELLY_MAX_COLOR)) {
441             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_BLUE));
442         } else if ((col.red == 0) && (col.green == 0) && (col.blue == 0) && (col.white == SHELLY_MAX_COLOR)) {
443             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_WHITE));
444         }
445     }
446
447     private void sendColors(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils oldCol,
448             ShellyColorUtils newCol, boolean autoOn) throws ShellyApiException {
449         // boolean updated = false;
450         Integer channelId = lightId + 1;
451         Map<String, String> parms = new TreeMap<>();
452
453         logger.trace(
454                 "{}: New color settings for channel {}: RGB {}/{}/{}, white={}, gain={}, brightness={}, color-temp={}",
455                 thingName, channelId, newCol.red, newCol.green, newCol.blue, newCol.white, newCol.gain,
456                 newCol.brightness, newCol.temp);
457         if (autoOn && (newCol.brightness >= 0)) {
458             parms.put(SHELLY_LIGHT_TURN, profile.inColor || newCol.brightness > 0 ? SHELLY_API_ON : SHELLY_API_OFF);
459         }
460         if (profile.inColor) {
461             if (oldCol.red != newCol.red || oldCol.green != newCol.green || oldCol.blue != newCol.blue
462                     || oldCol.white != newCol.white) {
463                 logger.debug("{}: Setting RGBW to {}/{}/{}/{}", thingName, newCol.red, newCol.green, newCol.blue,
464                         newCol.white);
465                 parms.put(SHELLY_COLOR_RED, String.valueOf(newCol.red));
466                 parms.put(SHELLY_COLOR_GREEN, String.valueOf(newCol.green));
467                 parms.put(SHELLY_COLOR_BLUE, String.valueOf(newCol.blue));
468                 parms.put(SHELLY_COLOR_WHITE, String.valueOf(newCol.white));
469             }
470         }
471         if ((!profile.inColor) && (oldCol.temp != newCol.temp)) {
472             logger.debug("{}: Setting color temp to {}", thingName, newCol.temp);
473             parms.put(SHELLY_COLOR_TEMP, String.valueOf(newCol.temp));
474         }
475         if (oldCol.gain != newCol.gain) {
476             logger.debug("{}: Setting gain to {}", thingName, newCol.gain);
477             parms.put(SHELLY_COLOR_GAIN, String.valueOf(newCol.gain));
478         }
479         if ((newCol.brightness >= 0) && (!profile.inColor || profile.isBulb)
480                 && (oldCol.brightness != newCol.brightness)) {
481             logger.debug("{}: Setting brightness to {}", thingName, newCol.brightness);
482             parms.put(SHELLY_COLOR_BRIGHTNESS, String.valueOf(newCol.brightness));
483         }
484         if (!oldCol.effect.equals(newCol.effect)) {
485             logger.debug("{}: Setting effect to {}", thingName, newCol.effect);
486             parms.put(SHELLY_COLOR_EFFECT, newCol.effect.toString());
487         }
488         if (!parms.isEmpty()) {
489             logger.debug("{}: Send light settings: {}", thingName, parms);
490             api.setLightParms(lightId, parms);
491             updateCurrentColors(lightId, newCol);
492         }
493     }
494
495     private void updateCurrentColors(int lightId, ShellyColorUtils col) {
496         channelColors.replace(lightId, col);
497         logger.debug("{}: Colors updated for lightId {}: RGBW={}/{}/{}/{}, Sat/Gain={}, Bright={}, Temp={} ", thingName,
498                 lightId, col.red, col.green, col.blue, col.white, col.gain, col.brightness, col.temp);
499     }
500
501     private int getColorFromHSB(PercentType colorPercent) {
502         return getColorFromHSB(colorPercent, SATURATION_FACTOR);
503     }
504
505     private int getColorFromHSB(PercentType colorPercent, double factor) {
506         double value = Math.round(colorPercent.doubleValue() * factor);
507         logger.trace("{}: convert {}% into {}/{} (factor={})", thingName, colorPercent, value, (int) value, factor);
508         return (int) value;
509     }
510 }