Skip to content

Instantly share code, notes, and snippets.

@sunnygleason
Created August 28, 2016 22:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sunnygleason/a92d40be61aad6742de391f4ea44e8cb to your computer and use it in GitHub Desktop.
Save sunnygleason/a92d40be61aad6742de391f4ea44e8cb to your computer and use it in GitHub Desktop.
Liftmaster Garage Control Integration w/ PubNub and Node.JS
var CTRL_CHAN, DOOR_STATES, HOME_CHAN, LIFTMASTER_PASSWORD, LIFTMASTER_USERNAME,
MyQ, PUB_KEY, PubNub, SUB_KEY, garage, initPubNub, makeHandler, pubnubConns,
refreshStatus, _;
_ = require('underscore');
MyQ = require('liftmaster');
PubNub = require('pubnub');
LIFTMASTER_USERNAME = 'YOUR_LIFTMASTER_USERNAME';
LIFTMASTER_PASSWORD = 'YOUR_LIFTMASTER_PASSWORD';
PUB_KEY = 'YOUR_PUB_KEY';
SUB_KEY = 'YOUR_SUB_KEY';
HOME_CHAN = 'MyHome';
CTRL_CHAN = 'MyHome_Ctrl';
DOOR_STATES = {
'0': 'closed',
'1': 'open',
'2': 'closed',
'4': 'opening',
'5': 'closing'
};
pubnubConns = {};
garage = new MyQ(LIFTMASTER_USERNAME, LIFTMASTER_PASSWORD);
makeHandler = function(uuid) {
return function(pnMessage) {
var command, newState;
if (!((pnMessage.subscribedChannel === CTRL_CHAN) && (pnMessage.message.target === uuid))) {
return;
}
command = pnMessage.message;
if (!pubnubConns[uuid]) {
return;
}
newState = (command.newState === "open") ? "1" : "0";
garage.setDoorState(uuid, newState, function() {
console.log("SETTING DOOR STATE to: " + JSON.stringify({ uuid: uuid, newState: newState }));
});
};
};
initPubNub = function() {
garage.getDevices(function(err, devices) {
_(devices).forEach(function(door) {
var handler, pn, uuid;
uuid = door.id;
door.type = 'Garage Door';
pn = new PubNub({
publishKey: PUB_KEY,
subscribeKey: SUB_KEY,
uuid: uuid,
ssl: true
});
pn.setState({
channels: [HOME_CHAN, CTRL_CHAN],
state: door
});
pn.publish({
channel: HOME_CHAN,
message: door
});
pn.subscribe({
channels: [HOME_CHAN, CTRL_CHAN],
withPresence: true
});
handler = makeHandler(uuid);
pn.addListener({
status: handler,
message: handler,
presence: handler
});
pubnubConns[uuid] = pn;
});
});
};
refreshStatus = function() {
garage.getDevices(function(err, devices) {
if (err) {
throw err;
}
_(devices).forEach(function(door) {
var pn, uuid;
door.type = 'Garage Door';
uuid = door.id;
pn = pubnubConns[uuid];
pn.setState({
channels: [HOME_CHAN, CTRL_CHAN],
state: door
});
pn.publish({
channel: HOME_CHAN,
message: door
});
});
});
};
garage.login(function(err, res) {
if (err) {
throw err;
}
console.log('logged in', JSON.stringify(res));
initPubNub();
setInterval(refreshStatus, 3000);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment