Skip to content

Instantly share code, notes, and snippets.

@mguinada
Forked from jamesbulpin/hue.js
Created February 19, 2021 19:34
Show Gist options
  • Save mguinada/249e17b2e41aa703df70ee5256e90073 to your computer and use it in GitHub Desktop.
Save mguinada/249e17b2e41aa703df70ee5256e90073 to your computer and use it in GitHub Desktop.

Revisions

  1. @jamesbulpin jamesbulpin created this gist Dec 4, 2016.
    71 changes: 71 additions & 0 deletions hue.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,71 @@
    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);
    }
    }
    });