routes.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. module.exports = {
  3. init: init,
  4. getConfig: getGeneric('getConfig'),
  5. getFullState: getGeneric('getFullState'),
  6. getLights: getGeneric('lights'),
  7. setLight: setLight
  8. };
  9. var hue = require('node-hue-api'),
  10. HueApi = hue.HueApi,
  11. lightState = hue.lightState,
  12. Color = require('color');
  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 t' + name);
  22. res.send(200, result);
  23. });
  24. };
  25. }
  26. function setLight(req, res) {
  27. console.log('set light: %s', req.params.id, req.body);
  28. var state = lightState.create();
  29. if (req.body.reset) state.reset();
  30. if (req.body.colorLoop) state.colorLoop();
  31. if (typeof req.body.state !== 'undefined') {
  32. if (req.body.state) state.on();
  33. else state.off();
  34. }
  35. if (req.body.color) {
  36. var color = new Color(req.body.color);
  37. state.rgb(color.rgb().array());
  38. }
  39. api.setLightState(req.params.id, state, function (error, result) {
  40. if (error) return res.send(500, error);
  41. res.send(200, {});
  42. });
  43. }