Skip to content

Instantly share code, notes, and snippets.

@threez
Created April 19, 2014 18:11
Show Gist options
  • Save threez/11092610 to your computer and use it in GitHub Desktop.
Save threez/11092610 to your computer and use it in GitHub Desktop.
Use ban to turn off/on the light if the door was opened
#!/usr/bin/env node
var WebSocketClient = require('websocket').client,
client = new WebSocketClient(),
url = 'ws://localhost:8080/',
light = '11011C';
function handleMessage(connection, data) {
var now = new Date();
// door was opened turn on the light
if (data['door-opened']) {
if (now.getHours() >= 20 || now.getHours() <= 6) { // at night
console.log('turn the lights on');
connection.sendUTF(JSON.stringify({
'rc-turn-on': { 'address': light }
}));
} else {
console.log('not dark at the moment so turn off the lights');
}
}
// door was closed turn of the light in 2 minutes
if (data['door-closed']) {
console.log('turn the lights off in 2min');
setTimeout(function() {
console.log('turning the lights off now');
connection.sendUTF(JSON.stringify({
'rc-turn-off': { 'address': light }
}));
}, 2 * 60 * 1000);
}
}
client.on('connectFailed', function(error) {
console.log('Connect Error:', error.toString(), 'reconnecting in 5 sec.');
setTimeout(function() {
client.connect(url);
}, 5000);
});
client.on('connect', function(connection) {
console.log('WebSocket client connected');
connection.on('error', function(error) {
console.error("Connection Error: " + error.toString());
});
connection.on('close', function() {
console.log('echo-protocol Connection Closed, reconnecting in 5 sec.');
setTimeout(function() {
client.connect(url);
}, 5000);
});
connection.on('message', function(message) {
var data = {};
if (message.type === 'utf8') {
data = JSON.parse(message.utf8Data);
}
handleMessage(connection, data);
});
});
client.connect(url);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment