Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@jamesbulpin
Created September 8, 2016 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamesbulpin/d09646331ee08e798a88473470d78145 to your computer and use it in GitHub Desktop.
Save jamesbulpin/d09646331ee08e798a88473470d78145 to your computer and use it in GitHub Desktop.
Control LightwaveRF lights based on MQTT messages
var LightwaveRF = require("lightwaverf");
var mqtt = require('mqtt');
var config_lwrf = require("../config/config_lwrf.js");
var lw = new LightwaveRF({ip:"10.52.2.118"});
function LWRFController(lw) {
this.timeout = 100;
this.queue = [];
this.ready = true;
this.lw = lw;
}
LWRFController.prototype.exec = function() {
this.queue.push(arguments);
this.process();
}
LWRFController.prototype.send = function(cmd, roomnum, devnum) {
var self = this;
switch(cmd) {
case "on":
this.lw.turnDeviceOn(roomnum, devnum, function() {
setTimeout(function() {
self.ready = true;
self.process();
}, 100);
});
break;
case "off":
this.lw.turnDeviceOff(roomnum, devnum, function() {
setTimeout(function() {
self.ready = true;
self.process();
}, 100);
});
break;
}
}
LWRFController.prototype.process = function() {
if (this.queue.length === 0) return;
if (!this.ready) return;
var self = this;
this.ready = false;
this.send.apply(this, this.queue.shift());
};
var lwrfctrl = new LWRFController(lw);
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 == 3) {
try {
id = config_lwrf.getDeviceId(tparts[1], tparts[2]);
console.log("Found LWRF device " + id[0] + "/" + id[1]);
switch(message.toString()) {
case 'on':
lwrfctrl.exec("on", id[0], id[1]);
client.publish("Log/LWRF/" + tparts[1] + "/" + tparts[2], 'on');
break;
case 'off':
lwrfctrl.exec("off", id[0], id[1]);
client.publish("Log/LWRF/" + tparts[1] + "/" + tparts[2], 'off');
break;
case 'dim':
//lwrfctrl.exec("dim", id[0], id[1]);(id[0], id[1], dimValue);
//client.publish("Log/LWRF/" + tparts[1] + "/" + tparts[2], 'dimXXX');
break;
}
}
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