routes.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. module.exports = {
  3. init: init,
  4. getConfig: getGeneric('getConfig'),
  5. getFullState: getGeneric('getFullState'),
  6. getLights: getGeneric('lights'),
  7. getLight: getLight,
  8. setLight: setLight
  9. };
  10. var hue = require('node-hue-api'),
  11. HueApi = hue.HueApi,
  12. lightState = hue.lightState,
  13. Color = require('color');
  14. var api = null;
  15. function init(hueConfig, callback) {
  16. api = new HueApi(hueConfig.host, hueConfig.username);
  17. callback();
  18. }
  19. function getGeneric(name) {
  20. return function (req, res) {
  21. api[name](function (error, result) {
  22. if (error) return res.send(500, 'Unable to get ' + name);
  23. res.send(200, result);
  24. });
  25. };
  26. }
  27. function getLight(req, res) {
  28. api.lightStatus(req.params.id, function (error, result) {
  29. if (error) return res.send(500, 'Unable to get state of light ' + req.params.id);
  30. res.send(200, result);
  31. });
  32. }
  33. function setLight(req, res) {
  34. console.log('set light: %s', req.params.id, req.body);
  35. var state = lightState.create();
  36. if (req.body.reset) state.reset();
  37. if (req.body.colorLoop) state.colorLoop();
  38. if (typeof req.body.state !== 'undefined') {
  39. if (req.body.state) state.on();
  40. else state.off();
  41. }
  42. if (req.body.color) {
  43. var color = new Color(req.body.color);
  44. state.rgb(color.rgb().array());
  45. }
  46. api.setLightState(req.params.id, state, function (error, result) {
  47. if (error) return res.send(500, error);
  48. res.send(200, {});
  49. });
  50. }