2 * Copyright (c) 2010-2023 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.io.imperihome.internal.model.device;
15 import java.math.BigDecimal;
16 import java.math.RoundingMode;
18 import org.apache.commons.lang3.StringUtils;
19 import org.openhab.core.items.Item;
20 import org.openhab.core.library.types.HSBType;
21 import org.openhab.core.library.types.PercentType;
22 import org.openhab.core.types.State;
23 import org.openhab.io.imperihome.internal.model.param.DeviceParam;
24 import org.openhab.io.imperihome.internal.model.param.ParamType;
29 * @author Pepijn de Geus - Initial contribution
31 public class RgbLightDevice extends AbstractEnergyLinkDevice {
33 public RgbLightDevice(Item item) {
34 super(DeviceType.RGB_LIGHT, item);
38 public void stateUpdated(Item item, State newState) {
39 super.stateUpdated(item, newState);
41 boolean status = false;
43 String color = "00000000";
45 State state = item.getStateAs(HSBType.class);
46 boolean isHsbState = state instanceof HSBType;
48 // State can be of UndefType, even with the getStateAs above
50 HSBType hsbState = (HSBType) state;
51 PercentType[] rgb = hsbState.toRGB();
53 // Set state to ON if any channel > 0
54 boolean isOn = rgb[0].doubleValue() > 0 || rgb[1].doubleValue() > 0 || rgb[2].doubleValue() > 0;
60 int r = convertPercentToByte(rgb[0]) & 0xFF;
61 int g = convertPercentToByte(rgb[1]) & 0xFF;
62 int b = convertPercentToByte(rgb[2]) & 0xFF;
63 color = (isOn ? "FF" : "00") + toHex(r) + toHex(g) + toHex(b);
66 State pState = item.getStateAs(PercentType.class);
67 if (pState instanceof PercentType) {
68 level = ((PercentType) pState).intValue();
74 addParam(new DeviceParam(ParamType.STATUS, status ^ isInverted() ? "1" : "0"));
75 addParam(new DeviceParam(ParamType.LEVEL, String.valueOf(level)));
76 addParam(new DeviceParam(ParamType.DIMMABLE, "0"));
77 addParam(new DeviceParam(ParamType.WHITE_CHANNEL, "1"));
78 addParam(new DeviceParam(ParamType.COLOR, color));
81 private String toHex(int value) {
82 String hex = Integer.toHexString(value);
83 return StringUtils.leftPad(hex, 2, '0');
86 private int convertPercentToByte(PercentType percent) {
87 return percent.toBigDecimal().multiply(BigDecimal.valueOf(255))
88 .divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP).intValue();