« What makes a good pull request description? | Main | Michael Pollan Doesn't Understand Paleo »

Mapping RGB colors to Philips Hue colors

Converting to Philips Hue color descriptors from colors picked in a web UI can be a bit tricky. Here's what I've come up with, which gets pretty close. The color descriptor is described in the Hue API docs (free account required). There are several other js libraries that work with Hue, but I wanted to build my own.

I'm using the jQuery Color plugin to convert RGB to HSV. Tinycolor will work too, but I went with jQuery Color because it allows CSS transitions with $.anmiate.

Here's the code:

var HueService = {
  colorToHueHsv: function (color) {
    var jqc = $.Color(color);
     return {
       "hue" : Math.floor(65535 * jqc.hue() / 360),
       "sat": Math.floor(jqc.saturation() * 255),
       "bri": Math.floor(jqc.lightness() * 255)

The input to the function can be anything that jQuery Color can interpret as a color. For instance, there's a lilac color I like, #676de8.

So I can do HueService.colorToHueHsv('#676de8') and get back {hue: 43143, sat: 187, bri: 167}.

I then turn on one of my lights to that color with a PUT to with form data {"on":true,"hue":43143,"sat":187,"bri":167}

Assuming I've authenticated to the Hue bridge, the light turns on with pretty much that color. I don't think I have the brightness and saturation mapped quite correctly; it's tricky because the Hue 0-1 space for brightness has 0 at "the lowest brightness possible with the bulb still on". I'll keep tuning this -- check the source for updates.

I'm using this code in my Sunrise Hues project, which lets me build custom sunrises as a gentle alarm clock.