routes.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. var api = null;
  14. function init(hueConfig, callback) {
  15. api = new HueApi(hueConfig.host, hueConfig.username);
  16. callback();
  17. }
  18. function getGeneric(name) {
  19. return function (req, res) {
  20. api[name](function (error, result) {
  21. if (error) return res.send(500, 'Unable to get ' + name);
  22. res.send(200, result);
  23. });
  24. };
  25. }
  26. function getLight(req, res) {
  27. api.lightStatusWithRGB(req.params.id, function (error, result) {
  28. if (error) return res.send(500, 'Unable to get state of light ' + req.params.id);
  29. // id is not part of the light status api
  30. result.id = req.params.id;
  31. res.send(200, result);
  32. });
  33. }
  34. function setLight(req, res) {
  35. console.log('set light: %s', req.params.id, req.body);
  36. var state = lightState.create();
  37. if (req.body.reset) state.reset();
  38. if (req.body.colorLoop) state.colorLoop();
  39. if (typeof req.body.on !== 'undefined') {
  40. if (req.body.on) state.on();
  41. else state.off();
  42. }
  43. if (req.body.rgb) {
  44. state.rgb(req.body.rgb);
  45. }
  46. if (req.body.bri) {
  47. state.bri(req.body.bri);
  48. }
  49. api.setLightState(req.params.id, state, function (error, result) {
  50. if (error) return res.send(500, error);
  51. res.send(200, {});
  52. });
  53. }