Skip to content

Instantly share code, notes, and snippets.

@jamesbulpin
Created December 4, 2016 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jamesbulpin/713d3bd47ff49a74e99f41672a3de3d0 to your computer and use it in GitHub Desktop.
Save jamesbulpin/713d3bd47ff49a74e99f41672a3de3d0 to your computer and use it in GitHub Desktop.
Service to control Philips Hue lights in response to MQTT messages
require('es6-promise').polyfill();
var hue = require("node-hue-api"),
HueApi = hue.HueApi,
lightState = hue.lightState;
var mqtt = require('mqtt');
var schedule = require('node-schedule');
// Exit once an hour to force a re-read of the Hue lights list
var j = schedule.scheduleJob(new Date((new Date()).getTime()+3600000), function() {
console.log("[" + new Date() + "] " + "Exiting after pre-set delay.");
process.exit(0);
});
var config_hue = require("../config/config_hue.js");
var lights = {};
console.log("Connecting to Hue hub " + config_hue.HUB + " as user " + config_hue.USERNAME);
api = new HueApi(config_hue.HUB, config_hue.USERNAME);
state0 = lightState.create().turnOff();
state1 = lightState.create().turnOn().bri(255);
// Populate the lightname=>id lookup table
function extractLightList(result) {
//console.log(result);
result.lights.forEach(function (l) {
lights[l.name] = l.id;
console.log("Found light '" + l.name + "' with id=" + l.id);
});
}
api.lights().then(extractLightList).done();
var client = mqtt.connect('mqtt://localhost', {protocolId: 'MQIsdp', protocolVersion: 3});
client.on('connect', function () {
console.log("Connected to MQTT");
client.subscribe('Light/#');
});
client.on('message', function (topic, message) {
console.log("MQTT RX t=" + topic + " m=" + message.toString());
var tparts = topic.split('/');
if (tparts.length == 2) {
try {
if (tparts[1] in lights) {
var id = lights[tparts[1]];
console.log("Using Hue device " + tparts[1] + " id=" + id);
switch(message.toString()) {
case 'on':
api.setLightState(id, state1).done();
client.publish("Log/Hue/" + tparts[1], 'on');
break;
case 'off':
api.setLightState(id, state0).done();
client.publish("Log/Hue/" + tparts[1], 'off');
break;
}
var dim = parseInt(message.toString());
if ((dim >= 0) && (dim <= 255)) {
api.setLightState(id, lightState.create().on().bri(dim)).done();
client.publish("Log/Hue/" + tparts[1], 'dim=' + message.toString());
}
}
}
catch (err) {
console.log("Error: " + err.message);
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment