Because there are regular questions on how to read the Color Items’ values as 24-bit RGB ranging from 0-255 I just wrote this little explanation how and why it works. (Or at least one of the many ways)
Let’s say you have a Color
item named aacc_color
. With this rule you can read out the R, G and B values from it:
rule "get RGB Colors from ColorItem"
when
Item aacc_color received command
then
val red = (receivedCommand as HSBType).red * 2.55
val green = (receivedCommand as HSBType).green * 2.55
val blue = (receivedCommand as HSBType).blue * 2.55
end
aacc_color
is the name of my Color item.
aacc_color.state
contains the State object of the Color item. Not really useful for us. So we need to convert it to something that really represents colors. In OpenHAB and OpenHAB2 this is the HSBType, which essentially is Hue, Saturation and Brightness.
(aacc_color.state as HSBType)
is our Color item. Now it’s not an OpenHAB State object anymore, but a useful color type. If we are interested in the RED, GREEN and BLUE values, we need another step.
(aacc_color.state as HSBType).red
contains the percentage of red color. This is returned as a PercentType. Yet, I want to have it as a number, ranging from 0 to 255 to control my lights. This can be done through simple maths.
(aacc_color.state as HSBType).red * 2.55
represents your amount of red between 0 (no red at all) and 255 (full brightness red).
Now you can take your variables and sent commands to other items that may be your RGB light bulbs, or in my case, my DIY MySensors 2,4GHz remote controlled china LED RGB Strips:
rule "Set RGB LEDs from Color item using ColorPicker"
when
Item aacc_color received command
then
val red = (receivedCommand as HSBType).red * 2.55
val green = (receivedCommand as HSBType).green * 2.55
val blue = (receivedCommand as HSBType).blue * 2.55
aacc_color_r.sendCommand(red)
aacc_color_g.sendCommand(green)
aacc_color_b.sendCommand(blue)
end
Brotip: While using any editor of your choice is fine for writing simple rules, you really should consider using the Eclipse SmartHome IDE for more complicated things like casting Item states to different types. Errors will show up instantly and you have integrated JavaDoc documenatation. This will save you a lot of time and hair.
Bonus content
You can also make use of your own new color-handling code to have functioning ON and OFF buttons near the colorpicker:
rule "Luminium Color Item"
when
Item aacc_color received command
then
if (receivedCommand instanceof HSBType)
{
val red = (receivedCommand as HSBType).red * 2.55
val green = (receivedCommand as HSBType).green * 2.55
val blue = (receivedCommand as HSBType).blue * 2.55
aacc_color_r.sendCommand(red)
aacc_color_g.sendCommand(green)
aacc_color_b.sendCommand(blue)
}
else if (receivedCommand == ON){
aacc_color.sendCommand(new HSBType("23,60,100"))
}
else if (receivedCommand == OFF){
aacc_mode.sendCommand(0) // Fade-out lights very slowly. Implemented in the device code
}
end
Enjoy your colors.