]> git.basschouten.com Git - openhab-addons.git/blob
c98575e51628897eeba387283d99fe87e4e02e4c
[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.device.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, OnOffType.from(value > 0));
176                     break;
177
178                 case CHANNEL_COLOR_TEMP:
179                     Integer temp = -1;
180                     if (command instanceof PercentType percentCommand) {
181                         logger.debug("{}: Set color temp to {}%", thingName, percentCommand.floatValue());
182                         Float percent = percentCommand.floatValue() / 100;
183                         temp = new DecimalType(col.minTemp + ((col.maxTemp - col.minTemp)) * percent).intValue();
184                         logger.debug("{}: Converted color-temp {}% to {}K (from Percent to Integer)", thingName,
185                                 percent, temp);
186                     } else if (command instanceof DecimalType decimalCommand) {
187                         temp = decimalCommand.intValue();
188                         logger.debug("{}: Set color temp to {}K (Integer)", thingName, temp);
189                     }
190                     validateRange(CHANNEL_COLOR_TEMP, temp, col.minTemp, col.maxTemp);
191                     col.setTemp(temp);
192                     col.brightness = -1;
193                     break;
194
195                 case CHANNEL_COLOR_EFFECT:
196                     Integer effect = ((DecimalType) command).intValue();
197                     logger.debug("{}: Set color effect to {}", thingName, effect);
198                     validateRange("effect", effect, SHELLY_MIN_EFFECT, SHELLY_MAX_EFFECT);
199                     col.setEffect(effect.intValue());
200             }
201
202             if (update) {
203                 // check for switching color mode
204                 if (profile.isBulb && !col.mode.isEmpty() && !col.mode.equals(oldCol.mode)) {
205                     logger.debug("{}: Color mode changed from {} to {}, set new mode", thingName, oldCol.mode,
206                             col.mode);
207                     api.setLightMode(col.mode);
208                 }
209
210                 // send changed colors to the device
211                 sendColors(profile, lightId, oldCol, col, config.brightnessAutoOn);
212             }
213             return true;
214         } catch (ShellyApiException e) {
215             logger.debug("{}: Unable to handle command: {}", thingName, e.toString());
216             return false;
217         } catch (IllegalArgumentException e) {
218             logger.debug("{}: Unable to handle command", thingName, e);
219             return false;
220         }
221     }
222
223     @SuppressWarnings("deprecation")
224     private boolean handleColorPicker(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils col,
225             Command command) throws ShellyApiException {
226         boolean updated = false;
227         if (command instanceof HSBType hsb) {
228             logger.debug("HSB-Info={}, Hue={}, getRGB={}, toRGB={}/{}/{}", hsb, hsb.getHue(),
229                     String.format("0x%08X", hsb.getRGB()), hsb.toRGB()[0], hsb.toRGB()[1], hsb.toRGB()[2]);
230             if (hsb.toString().contains("360,")) {
231                 logger.trace("{}: need to fix the Hue value (360->0)", thingName);
232                 HSBType fixHue = new HSBType(new DecimalType(0), hsb.getSaturation(), hsb.getBrightness());
233                 hsb = fixHue;
234             }
235
236             col.setRed(getColorFromHSB(hsb.getRed()));
237             col.setBlue(getColorFromHSB(hsb.getBlue()));
238             col.setGreen(getColorFromHSB(hsb.getGreen()));
239             col.setBrightness(getColorFromHSB(hsb.getBrightness(), BRIGHTNESS_FACTOR));
240             // white, gain and temp are not part of the HSB color scheme
241             updated = true;
242         } else if (command instanceof PercentType percentCommand) {
243             if (!profile.inColor || profile.isBulb) {
244                 col.brightness = SHELLY_MAX_BRIGHTNESS * percentCommand.intValue();
245                 updated = true;
246             }
247         } else if (command instanceof OnOffType onOffCommand) {
248             logger.debug("{}: Switch light {}", thingName, onOffCommand);
249             api.setLightParm(lightId, SHELLY_LIGHT_TURN, onOffCommand == OnOffType.ON ? SHELLY_API_ON : SHELLY_API_OFF);
250             col.power = onOffCommand;
251         } else if (command instanceof IncreaseDecreaseType) {
252             if (!profile.inColor || profile.isBulb) {
253                 logger.debug("{}: {} brightness by {}", thingName, command, SHELLY_DIM_STEPSIZE);
254                 PercentType percent = (PercentType) super.getChannelValue(CHANNEL_GROUP_COLOR_CONTROL,
255                         CHANNEL_BRIGHTNESS);
256                 int currentBrightness = percent.intValue() * SHELLY_MAX_BRIGHTNESS;
257                 int newBrightness = currentBrightness;
258                 if (command == IncreaseDecreaseType.DECREASE) {
259                     newBrightness = Math.max(currentBrightness - SHELLY_DIM_STEPSIZE, 0);
260                 } else {
261                     newBrightness = Math.min(currentBrightness + SHELLY_DIM_STEPSIZE, SHELLY_MAX_BRIGHTNESS);
262                 }
263                 col.brightness = newBrightness;
264                 updated = currentBrightness != newBrightness;
265             }
266         }
267         return updated;
268     }
269
270     private boolean handleFullColor(ShellyColorUtils col, Command command) throws IllegalArgumentException {
271         String color = command.toString().toLowerCase();
272         if (color.contains(",")) {
273             col.fromRGBW(color);
274         } else if (color.equals(SHELLY_COLOR_RED)) {
275             col.setRGBW(SHELLY_MAX_COLOR, 0, 0, 0);
276         } else if (color.equals(SHELLY_COLOR_GREEN)) {
277             col.setRGBW(0, SHELLY_MAX_COLOR, 0, 0);
278         } else if (color.equals(SHELLY_COLOR_BLUE)) {
279             col.setRGBW(0, 0, SHELLY_MAX_COLOR, 0);
280         } else if (color.equals(SHELLY_COLOR_YELLOW)) {
281             col.setRGBW(SHELLY_MAX_COLOR, SHELLY_MAX_COLOR, 0, 0);
282         } else if (color.equals(SHELLY_COLOR_WHITE)) {
283             col.setRGBW(0, 0, 0, SHELLY_MAX_COLOR);
284             col.setMode(SHELLY_MODE_WHITE);
285         } else {
286             throw new IllegalArgumentException("Invalid full color selection: " + color);
287         }
288         col.setMode(color.equals(SHELLY_MODE_WHITE) ? SHELLY_MODE_WHITE : SHELLY_MODE_COLOR);
289         return true;
290     }
291
292     private ShellyColorUtils getCurrentColors(int lightId) {
293         ShellyColorUtils col = channelColors.get(lightId);
294         if (col == null) {
295             col = new ShellyColorUtils(); // create a new entry
296             col.setMinMaxTemp(profile.minTemp, profile.maxTemp);
297             channelColors.put(lightId, col);
298             logger.trace("{}: Colors entry created for lightId {}", thingName, lightId);
299         } else {
300             logger.trace(
301                     "{}: Colors loaded for lightId {}: power={}, RGBW={}/{}/{}/{}, gain={}, brightness={}, color temp={} (min={}, max={}",
302                     thingName, lightId, col.power, col.red, col.green, col.blue, col.white, col.gain, col.brightness,
303                     col.temp, col.minTemp, col.maxTemp);
304         }
305         return col;
306     }
307
308     @Override
309     public boolean updateDeviceStatus(ShellySettingsStatus genericStatus) throws ShellyApiException {
310         if (!profile.isInitialized()) {
311             logger.debug("{}: Device not yet initialized!", thingName);
312             return false;
313         }
314         if (!profile.isLight) {
315             logger.debug("{}: ERROR: Device is not a light. but class ShellyHandlerLight is called!", thingName);
316         }
317
318         ShellyStatusLight status = api.getLightStatus();
319         logger.trace("{}: Updating light status in {} mode, {} channel(s)", thingName, profile.device.mode,
320                 status.lights.size());
321
322         // In white mode we have multiple channels
323         int lightId = 0;
324         boolean updated = false;
325         for (ShellyStatusLightChannel light : status.lights) {
326             Integer channelId = lightId + 1;
327             String controlGroup = buildControlGroupName(profile, channelId);
328             createLightChannels(light, lightId);
329             // The bulb has a combined channel set for color or white mode
330             // The RGBW2 uses 2 different thing types: color=1 channel, white=4 channel
331             if (profile.isBulb) {
332                 updateChannel(CHANNEL_GROUP_LIGHT_CONTROL, CHANNEL_LIGHT_COLOR_MODE, getOnOff(profile.inColor));
333             }
334
335             ShellyColorUtils col = getCurrentColors(lightId);
336             col.power = getOnOff(light.ison);
337
338             if (profile.settings.lights != null) {
339                 // Channel control/timer
340                 ShellySettingsRgbwLight ls = profile.settings.lights.get(lightId);
341                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_AUTOON,
342                         toQuantityType(getDouble(ls.autoOn), Units.SECOND));
343                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_AUTOOFF,
344                         toQuantityType(getDouble(ls.autoOff), Units.SECOND));
345                 updated |= updateChannel(controlGroup, CHANNEL_LIGHT_POWER, col.power);
346                 updated |= updateChannel(controlGroup, CHANNEL_TIMER_ACTIVE, getOnOff(light.hasTimer));
347                 updated |= updateChannel(controlGroup, CHANNEL_LIGHT_POWER, col.power);
348             }
349
350             if (getBool(light.overpower)) {
351                 postEvent(ALARM_TYPE_OVERPOWER, false);
352             }
353
354             if (profile.inColor) {
355                 logger.trace("{}: update color settings", thingName);
356                 col.setRGBW(getInteger(light.red), getInteger(light.green), getInteger(light.blue),
357                         getInteger(light.white));
358                 col.setGain(getInteger(light.gain));
359                 col.setEffect(getInteger(light.effect));
360
361                 String colorGroup = CHANNEL_GROUP_COLOR_CONTROL;
362                 logger.trace("{}: Update channels for group {}: RGBW={}/{}/{}, in %:{}%/{}%/{}%, white={}%, gain={}%",
363                         thingName, colorGroup, col.red, col.green, col.blue, col.percentRed, col.percentGreen,
364                         col.percentBlue, col.percentWhite, col.percentGain);
365                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_RED, col.percentRed);
366                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_GREEN, col.percentGreen);
367                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_BLUE, col.percentBlue);
368                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_WHITE, col.percentWhite);
369                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_GAIN, col.percentGain);
370                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_EFFECT, getDecimal(col.effect));
371                 setFullColor(colorGroup, col);
372
373                 logger.trace("{}: update {}.color picker", thingName, colorGroup);
374                 updated |= updateChannel(colorGroup, CHANNEL_COLOR_PICKER, col.toHSB());
375             }
376
377             if (!profile.inColor || profile.isBulb) {
378                 String whiteGroup = buildWhiteGroupName(profile, channelId);
379                 col.setBrightness(getInteger(light.brightness));
380                 updated |= updateChannel(whiteGroup, CHANNEL_BRIGHTNESS + "$Switch", col.power);
381                 updated |= updateChannel(whiteGroup, CHANNEL_BRIGHTNESS + "$Value",
382                         toQuantityType(col.power == OnOffType.ON ? col.percentBrightness.doubleValue() : 0, DIGITS_NONE,
383                                 Units.PERCENT));
384
385                 if ((profile.isBulb || profile.isDuo) && (light.temp != null)) {
386                     col.setTemp(getInteger(light.temp));
387                     updated |= updateChannel(whiteGroup, CHANNEL_COLOR_TEMP, col.percentTemp);
388                     logger.trace("{}: update {}.color picker", thingName, whiteGroup);
389                     updated |= updateChannel(whiteGroup, CHANNEL_COLOR_PICKER, col.toHSB());
390                 }
391             }
392
393             // continue with next light
394             lightId++;
395         }
396         return updated;
397     }
398
399     private void createLightChannels(ShellyStatusLightChannel status, int idx) {
400         if (!areChannelsCreated()) {
401             updateChannelDefinitions(ShellyChannelDefinitions.createLightChannels(getThing(), profile, status, idx));
402         }
403     }
404
405     private Integer setColor(Integer lightId, String colorName, Command command, Integer minValue, Integer maxValue)
406             throws ShellyApiException, IllegalArgumentException {
407         Integer value = -1;
408         logger.debug("{}: Set {} to {} ({})", thingName, colorName, command, command.getClass());
409         if (command instanceof PercentType percentCommand) {
410             double v = (double) maxValue * percentCommand.doubleValue() / 100.0;
411             value = (int) v;
412             logger.debug("{}: Value for {} is in percent: {}%={}", thingName, colorName, percentCommand, value);
413         } else if (command instanceof DecimalType decimalCommand) {
414             value = decimalCommand.intValue();
415             logger.debug("Value for {} is a number: {}", colorName, value);
416         } else if (command instanceof OnOffType onOffCommand) {
417             value = onOffCommand.equals(OnOffType.ON) ? SHELLY_MAX_COLOR : SHELLY_MIN_COLOR;
418             logger.debug("{}: Value for {} of type OnOff was converted to {}", thingName, colorName, value);
419         } else {
420             throw new IllegalArgumentException(
421                     "Invalid value type for " + colorName + ": " + value + " / type " + value.getClass());
422         }
423         validateRange(colorName, value, minValue, maxValue);
424         return value.intValue();
425     }
426
427     private Integer setColor(Integer lightId, String colorName, Command command, Integer maxValue)
428             throws ShellyApiException, IllegalArgumentException {
429         return setColor(lightId, colorName, command, 0, maxValue);
430     }
431
432     private void setFullColor(String colorGroup, ShellyColorUtils col) {
433         if ((col.red == SHELLY_MAX_COLOR) && (col.green == SHELLY_MAX_COLOR) && (col.blue == 0)) {
434             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_YELLOW));
435         } else if ((col.red == SHELLY_MAX_COLOR) && (col.green == 0) && (col.blue == 0)) {
436             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_RED));
437         } else if ((col.red == 0) && (col.green == SHELLY_MAX_COLOR) && (col.blue == 0)) {
438             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_GREEN));
439         } else if ((col.red == 0) && (col.green == 0) && (col.blue == SHELLY_MAX_COLOR)) {
440             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_BLUE));
441         } else if ((col.red == 0) && (col.green == 0) && (col.blue == 0) && (col.white == SHELLY_MAX_COLOR)) {
442             updateChannel(colorGroup, CHANNEL_COLOR_FULL, new StringType(SHELLY_COLOR_WHITE));
443         }
444     }
445
446     private void sendColors(ShellyDeviceProfile profile, Integer lightId, ShellyColorUtils oldCol,
447             ShellyColorUtils newCol, boolean autoOn) throws ShellyApiException {
448         // boolean updated = false;
449         Integer channelId = lightId + 1;
450         Map<String, String> parms = new TreeMap<>();
451
452         logger.trace(
453                 "{}: New color settings for channel {}: RGB {}/{}/{}, white={}, gain={}, brightness={}, color-temp={}",
454                 thingName, channelId, newCol.red, newCol.green, newCol.blue, newCol.white, newCol.gain,
455                 newCol.brightness, newCol.temp);
456         if (autoOn && (newCol.brightness >= 0)) {
457             parms.put(SHELLY_LIGHT_TURN, profile.inColor || newCol.brightness > 0 ? SHELLY_API_ON : SHELLY_API_OFF);
458         }
459         if (profile.inColor) {
460             if (oldCol.red != newCol.red || oldCol.green != newCol.green || oldCol.blue != newCol.blue
461                     || oldCol.white != newCol.white) {
462                 logger.debug("{}: Setting RGBW to {}/{}/{}/{}", thingName, newCol.red, newCol.green, newCol.blue,
463                         newCol.white);
464                 parms.put(SHELLY_COLOR_RED, String.valueOf(newCol.red));
465                 parms.put(SHELLY_COLOR_GREEN, String.valueOf(newCol.green));
466                 parms.put(SHELLY_COLOR_BLUE, String.valueOf(newCol.blue));
467                 parms.put(SHELLY_COLOR_WHITE, String.valueOf(newCol.white));
468             }
469         }
470         if ((!profile.inColor) && (oldCol.temp != newCol.temp)) {
471             logger.debug("{}: Setting color temp to {}", thingName, newCol.temp);
472             parms.put(SHELLY_COLOR_TEMP, String.valueOf(newCol.temp));
473         }
474         if (oldCol.gain != newCol.gain) {
475             logger.debug("{}: Setting gain to {}", thingName, newCol.gain);
476             parms.put(SHELLY_COLOR_GAIN, String.valueOf(newCol.gain));
477         }
478         if ((newCol.brightness >= 0) && (!profile.inColor || profile.isBulb)
479                 && (oldCol.brightness != newCol.brightness)) {
480             logger.debug("{}: Setting brightness to {}", thingName, newCol.brightness);
481             parms.put(SHELLY_COLOR_BRIGHTNESS, String.valueOf(newCol.brightness));
482         }
483         if (!oldCol.effect.equals(newCol.effect)) {
484             logger.debug("{}: Setting effect to {}", thingName, newCol.effect);
485             parms.put(SHELLY_COLOR_EFFECT, newCol.effect.toString());
486         }
487         if (!parms.isEmpty()) {
488             logger.debug("{}: Send light settings: {}", thingName, parms);
489             api.setLightParms(lightId, parms);
490             updateCurrentColors(lightId, newCol);
491         }
492     }
493
494     private void updateCurrentColors(int lightId, ShellyColorUtils col) {
495         channelColors.replace(lightId, col);
496         logger.debug("{}: Colors updated for lightId {}: RGBW={}/{}/{}/{}, Sat/Gain={}, Bright={}, Temp={} ", thingName,
497                 lightId, col.red, col.green, col.blue, col.white, col.gain, col.brightness, col.temp);
498     }
499
500     private int getColorFromHSB(PercentType colorPercent) {
501         return getColorFromHSB(colorPercent, SATURATION_FACTOR);
502     }
503
504     private int getColorFromHSB(PercentType colorPercent, double factor) {
505         double value = Math.round(colorPercent.doubleValue() * factor);
506         logger.trace("{}: convert {}% into {}/{} (factor={})", thingName, colorPercent, value, (int) value, factor);
507         return (int) value;
508     }
509 }