Merge pull request #147 from ntim/support_for_philips_hue

Support for philips hue

Former-commit-id: 6cdaeb838b00d00d5de2570339ef3da0375c44d6
This commit is contained in:
tvdzwan 2014-08-24 20:55:36 +02:00
commit 8d2da249ae
3 changed files with 291 additions and 253 deletions

View File

@ -165,7 +165,8 @@ LedDevice * LedDeviceFactory::construct(const Json::Value & deviceConfig)
else if (type == "philipshue")
{
const std::string output = deviceConfig["output"].asString();
device = new LedDevicePhilipsHue(output);
const bool switchOffOnBlack = deviceConfig.get("switchOffOnBlack", true).asBool();
device = new LedDevicePhilipsHue(output, switchOffOnBlack);
}
else if (type == "test")
{

View File

@ -1,4 +1,3 @@
#include <iostream>
// Local-Hyperion includes
#include "LedDevicePhilipsHue.h"
@ -11,8 +10,130 @@
#include <QHttpRequestHeader>
#include <QEventLoop>
LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output) :
host(output.c_str()), username("newdeveloper") {
#include <set>
bool operator ==(CiColor p1, CiColor p2) {
return (p1.x == p2.x) && (p1.y == p2.y) && (p1.bri == p2.bri);
}
bool operator !=(CiColor p1, CiColor p2) {
return !(p1 == p2);
}
PhilipsHueLamp::PhilipsHueLamp(unsigned int id, QString originalState, QString modelId) :
id(id), originalState(originalState) {
// Hue system model ids.
const std::set<QString> HUE_BULBS_MODEL_IDS = { "LCT001", "LCT002", "LCT003" };
const std::set<QString> LIVING_COLORS_MODEL_IDS = { "LLC001", "LLC005", "LLC006", "LLC007", "LLC011", "LLC012",
"LLC013", "LST001" };
// Find id in the sets and set the appropiate color space.
if (HUE_BULBS_MODEL_IDS.find(modelId) != HUE_BULBS_MODEL_IDS.end()) {
colorSpace.red = {0.675f, 0.322f};
colorSpace.green = {0.4091f, 0.518f};
colorSpace.blue = {0.167f, 0.04f};
} else if (LIVING_COLORS_MODEL_IDS.find(modelId) != LIVING_COLORS_MODEL_IDS.end()) {
colorSpace.red = {0.703f, 0.296f};
colorSpace.green = {0.214f, 0.709f};
colorSpace.blue = {0.139f, 0.081f};
} else {
colorSpace.red = {1.0f, 0.0f};
colorSpace.green = {0.0f, 1.0f};
colorSpace.blue = {0.0f, 0.0f};
}
// Initialize black color.
black = rgbToCiColor(0.0f, 0.0f, 0.0f);
// Initialize color with black
color = {black.x, black.y, black.bri};
}
float PhilipsHueLamp::crossProduct(CiColor p1, CiColor p2) {
return p1.x * p2.y - p1.y * p2.x;
}
bool PhilipsHueLamp::isPointInLampsReach(CiColor p) {
CiColor v1 = { colorSpace.green.x - colorSpace.red.x, colorSpace.green.y - colorSpace.red.y };
CiColor v2 = { colorSpace.blue.x - colorSpace.red.x, colorSpace.blue.y - colorSpace.red.y };
CiColor q = { p.x - colorSpace.red.x, p.y - colorSpace.red.y };
float s = crossProduct(q, v2) / crossProduct(v1, v2);
float t = crossProduct(v1, q) / crossProduct(v1, v2);
if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f)) {
return true;
}
return false;
}
CiColor PhilipsHueLamp::getClosestPointToPoint(CiColor a, CiColor b, CiColor p) {
CiColor AP = { p.x - a.x, p.y - a.y };
CiColor AB = { b.x - a.x, b.y - a.y };
float ab2 = AB.x * AB.x + AB.y * AB.y;
float ap_ab = AP.x * AB.x + AP.y * AB.y;
float t = ap_ab / ab2;
if (t < 0.0f) {
t = 0.0f;
} else if (t > 1.0f) {
t = 1.0f;
}
return {a.x + AB.x * t, a.y + AB.y * t};
}
float PhilipsHueLamp::getDistanceBetweenTwoPoints(CiColor p1, CiColor p2) {
// Horizontal difference.
float dx = p1.x - p2.x;
// Vertical difference.
float dy = p1.y - p2.y;
// Absolute value.
return sqrt(dx * dx + dy * dy);
}
CiColor PhilipsHueLamp::rgbToCiColor(float red, float green, float blue) {
// Apply gamma correction.
float r = (red > 0.04045f) ? powf((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f);
float g = (green > 0.04045f) ? powf((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f);
float b = (blue > 0.04045f) ? powf((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f);
// Convert to XYZ space.
float X = r * 0.649926f + g * 0.103455f + b * 0.197109f;
float Y = r * 0.234327f + g * 0.743075f + b * 0.022598f;
float Z = r * 0.0000000f + g * 0.053077f + b * 1.035763f;
// Convert to x,y space.
float cx = X / (X + Y + Z);
float cy = Y / (X + Y + Z);
if (isnan(cx)) {
cx = 0.0f;
}
if (isnan(cy)) {
cy = 0.0f;
}
// Brightness is simply Y in the XYZ space.
CiColor xy = { cx, cy, Y };
// Check if the given XY value is within the color reach of our lamps.
if (!isPointInLampsReach(xy)) {
// It seems the color is out of reach let's find the closes color we can produce with our lamp and send this XY value out.
CiColor pAB = getClosestPointToPoint(colorSpace.red, colorSpace.green, xy);
CiColor pAC = getClosestPointToPoint(colorSpace.blue, colorSpace.red, xy);
CiColor pBC = getClosestPointToPoint(colorSpace.green, colorSpace.blue, xy);
// Get the distances per point and see which point is closer to our Point.
float dAB = getDistanceBetweenTwoPoints(xy, pAB);
float dAC = getDistanceBetweenTwoPoints(xy, pAC);
float dBC = getDistanceBetweenTwoPoints(xy, pBC);
float lowest = dAB;
CiColor closestPoint = pAB;
if (dAC < lowest) {
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
lowest = dBC;
closestPoint = pBC;
}
// Change the xy value to a value which is within the reach of the lamp.
xy.x = closestPoint.x;
xy.y = closestPoint.y;
}
return xy;
}
LedDevicePhilipsHue::LedDevicePhilipsHue(const std::string& output, bool switchOffOnBlack) :
host(output.c_str()), username("newdeveloper"), switchOffOnBlack(switchOffOnBlack) {
http = new QHttp(host);
timer.setInterval(3000);
timer.setSingleShot(true);
@ -25,92 +146,63 @@ LedDevicePhilipsHue::~LedDevicePhilipsHue() {
int LedDevicePhilipsHue::write(const std::vector<ColorRgb> & ledValues) {
// Save light states if not done before.
if (!statesSaved())
saveStates(ledValues.size());
// Iterate through colors and set light states.
unsigned int lightId = 0;
for (const ColorRgb &color : ledValues) {
// Send only request to the brigde if color changed (prevents DDOS --> 503)
if (!oldLedValues.empty())
if(!hasColorChanged(lightId, &color)) {
lightId++;
continue;
if (!areStatesSaved()) {
saveStates((unsigned int) ledValues.size());
switchOn((unsigned int) ledValues.size());
}
float r = color.red / 255.0f;
float g = color.green / 255.0f;
float b = color.blue / 255.0f;
//set color gamut triangle
if(std::find(hueBulbs.begin(), hueBulbs.end(), modelIds[lightId]) != hueBulbs.end()) {
Red = {0.675f, 0.322f};
Green = {0.4091f, 0.518f};
Blue = {0.167f, 0.04f};
} else if (std::find(livingColors.begin(),
livingColors.end(), modelIds[lightId]) != livingColors.end()) {
Red = {0.703f, 0.296f};
Green = {0.214f, 0.709f};
Blue = {0.139f, 0.081f};
} else {
Red = {1.0f, 0.0f};
Green = {0.0f, 1.0f};
Blue = {0.0f, 0.0f};
}
// if color equal black, switch off lamp ...
if (r == 0.0f && g == 0.0f && b == 0.0f) {
switchLampOff(lightId);
lightId++;
continue;
}
// ... and if lamp off, switch on
if (!checkOnStatus(states[lightId]))
switchLampOn(lightId);
float bri;
CGPoint p = {0.0f, 0.0f};
// Scale colors from [0, 255] to [0, 1] and convert to xy space.
rgbToXYBrightness(r, g, b, p, bri);
// Send adjust color and brightness command in JSON format.
put(getStateRoute(lightId),
QString("{\"xy\": [%1, %2], \"bri\": %3}").arg(p.x).arg(p.y).arg(qRound(b * 255.0f)));
lightId++;
}
oldLedValues = ledValues;
timer.start();
// If there are less states saved than colors given, then maybe something went wrong before.
if (lamps.size() != ledValues.size()) {
restoreStates();
return 0;
}
// Iterate through colors and set light states.
unsigned int idx = 0;
for (const ColorRgb& color : ledValues) {
// Get lamp.
PhilipsHueLamp& lamp = lamps.at(idx);
// Scale colors from [0, 255] to [0, 1] and convert to xy space.
CiColor xy = lamp.rgbToCiColor(color.red / 255.0f, color.green / 255.0f, color.blue / 255.0f);
// Write color if color has been changed.
if (xy != lamp.color) {
// Switch on if the lamp has been previously switched off.
if (switchOffOnBlack && lamp.color == lamp.black) {
bool LedDevicePhilipsHue::hasColorChanged(unsigned int lightId, const ColorRgb *color) {
bool matchFound = true;
const ColorRgb &tmpOldColor = oldLedValues[lightId];
if ((*color).red == tmpOldColor.red)
matchFound = false;
if (!matchFound && (*color).green == tmpOldColor.green)
matchFound = false;
else
matchFound = true;
if (!matchFound && (*color).blue == tmpOldColor.blue)
matchFound = false;
else
matchFound = true;
}
// Send adjust color and brightness command in JSON format.
put(getStateRoute(lamp.id),
QString("{\"xy\": [%1, %2], \"bri\": %3}").arg(xy.x).arg(xy.y).arg(qRound(xy.bri * 255.0f)));
return matchFound;
}
// Switch lamp off if switchOffOnBlack is enabled and the lamp is currently on.
if (switchOffOnBlack) {
// From black to a color.
if (lamp.color == lamp.black && xy != lamp.black) {
put(getStateRoute(lamp.id), QString("{\"on\": true}"));
}
// From a color to black.
else if (lamp.color != lamp.black && xy == lamp.black) {
put(getStateRoute(lamp.id), QString("{\"on\": false}"));
}
}
// Remember last color.
lamp.color = xy;
// Next light id.
idx++;
}
timer.start();
return 0;
}
int LedDevicePhilipsHue::switchOff() {
timer.stop();
// If light states have been saved before, ...
if (statesSaved()) {
if (areStatesSaved()) {
// ... restore them.
restoreStates();
}
return 0;
}
bool LedDevicePhilipsHue::checkOnStatus(QString status) {
return status.contains("\"on\":true");
}
void LedDevicePhilipsHue::put(QString route, QString content) {
QString url = QString("/api/%1/%2").arg(username).arg(route);
QHttpRequestHeader header("PUT", url);
@ -142,7 +234,7 @@ QByteArray LedDevicePhilipsHue::get(QString route) {
}
QString LedDevicePhilipsHue::getStateRoute(unsigned int lightId) {
return QString("lights/%1/state").arg(lightId + 1);
return QString("lights/%1/state").arg(lightId);
}
QString LedDevicePhilipsHue::getRoute(unsigned int lightId) {
@ -150,9 +242,8 @@ QString LedDevicePhilipsHue::getRoute(unsigned int lightId) {
}
void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
// Clear saved light states.
states.clear();
modelIds.clear();
// Clear saved lamps.
lamps.clear();
// Use json parser to parse reponse.
Json::Reader reader;
Json::FastWriter writer;
@ -166,144 +257,35 @@ void LedDevicePhilipsHue::saveStates(unsigned int nLights) {
// Error occured, break loop.
break;
}
// Save state object values which are subject to change.
// Get state object values which are subject to change.
Json::Value state(Json::objectValue);
state["on"] = json["state"]["on"];
if (json["state"]["on"] == true) {
state["xy"] = json["state"]["xy"];
state["bri"] = json["state"]["bri"];
}
// Determine the model id.
QString modelId = QString(writer.write(json["modelid"]).c_str()).trimmed().replace("\"", "");
QString originalState = QString(writer.write(state).c_str()).trimmed();
// Save state object.
modelIds.push_back(QString(writer.write(json["modelid"]).c_str()).trimmed().replace("\"", ""));
states.push_back(QString(writer.write(state).c_str()).trimmed());
lamps.push_back(PhilipsHueLamp(i + 1, originalState, modelId));
}
}
void LedDevicePhilipsHue::switchLampOn(unsigned int lightId) {
put(getStateRoute(lightId), "{\"on\": true}");
states[lightId].replace("\"on\":false", "\"on\":true");
void LedDevicePhilipsHue::switchOn(unsigned int nLights) {
for (PhilipsHueLamp lamp : lamps) {
put(getStateRoute(lamp.id), "{\"on\": true}");
}
void LedDevicePhilipsHue::switchLampOff(unsigned int lightId) {
put(getStateRoute(lightId), "{\"on\": false}");
states[lightId].replace("\"on\":true", "\"on\":false");
}
void LedDevicePhilipsHue::restoreStates() {
unsigned int lightId = 0;
for (QString state : states) {
if (!checkOnStatus(states[lightId]))
switchLampOn(lightId);
put(getStateRoute(lightId), states[lightId]);
lightId++;
for (PhilipsHueLamp lamp : lamps) {
put(getStateRoute(lamp.id), lamp.originalState);
}
// Clear saved light states.
states.clear();
modelIds.clear();
oldLedValues.clear();
lamps.clear();
}
bool LedDevicePhilipsHue::statesSaved() {
return !states.empty();
}
float LedDevicePhilipsHue::CrossProduct(CGPoint& p1, CGPoint& p2) {
return (p1.x * p2.y - p1.y * p2.x);
}
bool LedDevicePhilipsHue::CheckPointInLampsReach(CGPoint& p) {
CGPoint v1 = {Green.x - Red.x, Green.y - Red.y};
CGPoint v2 = {Blue.x - Red.x, Blue.y - Red.y};
CGPoint q = {p.x - Red.x, p.y - Red.y};
float s = CrossProduct(q, v2) / CrossProduct(v1, v2);
float t = CrossProduct(v1, q) / CrossProduct(v1, v2);
if ((s >= 0.0f) && (t >= 0.0f) && (s + t <= 1.0f))
return true;
else
return false;
}
CGPoint LedDevicePhilipsHue::GetClosestPointToPoint(CGPoint& A, CGPoint& B, CGPoint& P) {
CGPoint AP = {P.x - A.x, P.y - A.y};
CGPoint AB = {B.x - A.x, B.y - A.y};
float ab2 = AB.x * AB.x + AB.y * AB.y;
float ap_ab = AP.x * AB.x + AP.y * AB.y;
float t = ap_ab / ab2;
if (t < 0.0f)
t = 0.0f;
else if (t > 1.0f)
t = 1.0f;
return {A.x + AB.x * t, A.y + AB.y * t};
}
float LedDevicePhilipsHue::GetDistanceBetweenTwoPoints(CGPoint& one, CGPoint& two) {
float dx = one.x - two.x; // horizontal difference
float dy = one.y - two.y; // vertical difference
float dist = sqrt(dx * dx + dy * dy);
return dist;
}
void LedDevicePhilipsHue::rgbToXYBrightness(float red, float green, float blue, CGPoint& xyPoint, float& brightness) {
//Apply gamma correction.
float r = (red > 0.04045f) ? powf((red + 0.055f) / (1.0f + 0.055f), 2.4f) : (red / 12.92f);
float g = (green > 0.04045f) ? powf((green + 0.055f) / (1.0f + 0.055f), 2.4f) : (green / 12.92f);
float b = (blue > 0.04045f) ? powf((blue + 0.055f) / (1.0f + 0.055f), 2.4f) : (blue / 12.92f);
//Convert to XYZ space.
float X = r * 0.649926f + g * 0.103455f + b * 0.197109f;
float Y = r * 0.234327f + g * 0.743075f + b * 0.022598f;
float Z = r * 0.0000000f + g * 0.053077f + b * 1.035763f;
//Convert to x,y space.
float cx = X / (X + Y + Z + 0.0000001f);
float cy = Y / (X + Y + Z + 0.0000001f);
if (isnan(cx))
cx = 0.0f;
if (isnan(cy))
cy = 0.0f;
xyPoint.x = cx;
xyPoint.y = cy;
//Check if the given XY value is within the colourreach of our lamps.
bool inReachOfLamps = CheckPointInLampsReach(xyPoint);
if (!inReachOfLamps) {
//It seems the colour is out of reach
//let's find the closes colour we can produce with our lamp and send this XY value out.
//Find the closest point on each line in the triangle.
CGPoint pAB = GetClosestPointToPoint(Red, Green, xyPoint);
CGPoint pAC = GetClosestPointToPoint(Blue, Red, xyPoint);
CGPoint pBC = GetClosestPointToPoint(Green, Blue, xyPoint);
//Get the distances per point and see which point is closer to our Point.
float dAB = GetDistanceBetweenTwoPoints(xyPoint, pAB);
float dAC = GetDistanceBetweenTwoPoints(xyPoint, pAC);
float dBC = GetDistanceBetweenTwoPoints(xyPoint, pBC);
float lowest = dAB;
CGPoint closestPoint = pAB;
if (dAC < lowest) {
lowest = dAC;
closestPoint = pAC;
}
if (dBC < lowest) {
lowest = dBC;
closestPoint = pBC;
}
//Change the xy value to a value which is within the reach of the lamp.
xyPoint.x = closestPoint.x;
xyPoint.y = closestPoint.y;
}
// Brightness is simply Y in the XYZ space.
brightness = Y;
bool LedDevicePhilipsHue::areStatesSaved() {
return !lamps.empty();
}

View File

@ -12,6 +12,101 @@
// Leddevice includes
#include <leddevice/LedDevice.h>
/**
* A color point in the color space of the hue system.
*/
struct CiColor {
/// X component.
float x;
/// Y component.
float y;
/// The brightness.
float bri;
};
bool operator==(CiColor p1, CiColor p2);
bool operator!=(CiColor p1, CiColor p2);
/**
* Color triangle to define an available color space for the hue lamps.
*/
struct CiColorTriangle {
CiColor red, green, blue;
};
/**
* Simple class to hold the id, the latest color, the color space and the original state.
*/
class PhilipsHueLamp {
public:
unsigned int id;
CiColor black;
CiColor color;
CiColorTriangle colorSpace;
QString originalState;
///
/// Constructs the lamp.
///
/// @param id the light id
///
/// @param originalState the json string of the original state
///
/// @param modelId the model id of the hue lamp which is used to determine the color space
///
PhilipsHueLamp(unsigned int id, QString originalState, QString modelId);
///
/// Converts an RGB color to the Hue xy color space and brightness.
/// https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
///
/// @param red the red component in [0, 1]
///
/// @param green the green component in [0, 1]
///
/// @param blue the blue component in [0, 1]
///
/// @return color point
///
CiColor rgbToCiColor(float red, float green, float blue);
///
/// @param p the color point to check
///
/// @return true if the color point is covered by the lamp color space
///
bool isPointInLampsReach(CiColor p);
///
/// @param p1 point one
///
/// @param p2 point tow
///
/// @return the cross product between p1 and p2
///
float crossProduct(CiColor p1, CiColor p2);
///
/// @param a reference point one
///
/// @param b reference point two
///
/// @param p the point to which the closest point is to be found
///
/// @return the closest color point of p to a and b
///
CiColor getClosestPointToPoint(CiColor a, CiColor b, CiColor p);
///
/// @param p1 point one
///
/// @param p2 point tow
///
/// @return the distance between the two points
///
float getDistanceBetweenTwoPoints(CiColor p1, CiColor p2);
};
/**
* Implementation for the Philips Hue system.
*
@ -20,13 +115,8 @@
* Framegrabber must be limited to 10 Hz / numer of lights to avoid rate limitation by the hue bridge.
* Create a new API user name "newdeveloper" on the bridge (http://developers.meethue.com/gettingstarted.html)
*
* @author ntim (github)
* @author ntim (github), bimsarck (github)
*/
struct CGPoint;
struct CGPoint {
float x;
float y;
};
class LedDevicePhilipsHue: public QObject, public LedDevice {
Q_OBJECT
public:
@ -35,7 +125,9 @@ public:
///
/// @param output the ip address of the bridge
///
LedDevicePhilipsHue(const std::string& output);
/// @param switchOffOnBlack kill lights for black
///
LedDevicePhilipsHue(const std::string& output, bool switchOffOnBlack);
///
/// Destructor of this device
@ -59,20 +151,8 @@ private slots:
void restoreStates();
private:
/// Available modelIds
const std::vector<QString> hueBulbs = {"LCT001", "LCT002", "LCT003"};
const std::vector<QString> livingColors = {"LLC001", "LLC005", "LLC006", "LLC007",
"LLC011", "LLC012", "LLC013", "LST001"};
/// Color gamut triangle
CGPoint Red , Green, Blue;
float CrossProduct(CGPoint& p1, CGPoint& p2);
bool CheckPointInLampsReach(CGPoint& p);
CGPoint GetClosestPointToPoint(CGPoint& A, CGPoint& B, CGPoint& P);
float GetDistanceBetweenTwoPoints(CGPoint& one, CGPoint& two);
/// Array to save the light states.
std::vector<QString> states;
/// Array to save the lamps.
std::vector<PhilipsHueLamp> lamps;
/// Ip address of the bridge
QString host;
/// User name for the API ("newdeveloper")
@ -81,13 +161,8 @@ private:
QHttp* http;
/// Use timer to reset lights when we got into "GRABBINGMODE_OFF".
QTimer timer;
std::vector<ColorRgb> oldLedValues;
std::vector<QString> modelIds;
bool hasColorChanged(unsigned int lightId, const ColorRgb *color);
bool checkOnStatus(QString status);
///
bool switchOffOnBlack;
///
/// Sends a HTTP GET request (blocking).
@ -133,31 +208,11 @@ private:
///
/// @param nLights the number of lights
///
void switchLampOn(unsigned int lightId);
void switchLampOff(unsigned int lightId);
void switchOn(unsigned int nLights);
///
/// @return true if light states have been saved.
///
bool statesSaved();
///
/// Converts an RGB color to the Hue xy color space and brightness
/// https://github.com/PhilipsHue/PhilipsHueSDK-iOS-OSX/blob/master/ApplicationDesignNotes/RGB%20to%20xy%20Color%20conversion.md
///
/// @param red the red component in [0, 1]
///
/// @param green the green component in [0, 1]
///
/// @param blue the blue component in [0, 1]
///
/// @param x converted x component
///
/// @param y converted y component
///
/// @param brightness converted brightness component
///
void rgbToXYBrightness(float red, float green, float blue, CGPoint& xyPoint, float& brightness);
bool areStatesSaved();
};