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