Skip to content

Instantly share code, notes, and snippets.

@rudiedirkx
Last active February 20, 2016 00:34
Show Gist options
  • Save rudiedirkx/0ff9c3e23f5c7fdc0cef to your computer and use it in GitHub Desktop.
Save rudiedirkx/0ff9c3e23f5c7fdc0cef to your computer and use it in GitHub Desktop.
// console.log(process.argv);
var port = parseInt(process.argv[2]);
if ( !port || isNaN(port) ) {
console.log('\nPort arg must be int.\n\n');
process.exit();
}
var status = [0, 0, 0, 0, 0, 0, 0, 0];
require('net').createServer(function(socket) {
console.log('\nNew connection...');
// socket.setEncoding('utf8');
function writeStatus() {
var dec = 0;
status.forEach(function(on, i) {
dec += on * Math.pow(2, i);
});
console.log('Writing status: ' + dec);
var buffer = new Buffer(1);
buffer[0] = dec;
socket.write(buffer);
}
socket.on('error', function(e) {
console.log(e);
});
socket.on('data', function(data) {
var cmd = data[0];
console.log('Incoming data...', cmd);
if ( cmd == 91 ) {
// get status
}
else if ( cmd == 100 ) {
// all on
status.forEach(function(on, i) {
status[i] = 1;
});
}
else if ( cmd >= 101 && cmd <= 108 ) {
// one on
var relayIndex = cmd - 100 - 1;
status[relayIndex] = 1;
}
else if ( cmd == 110 ) {
// all off
status.forEach(function(on, i) {
status[i] = 0;
});
}
else if ( cmd >= 111 && cmd <= 118 ) {
// one off
var relayIndex = cmd - 110 - 1;
status[relayIndex] = 0;
}
console.log('New status:', status.join(''));
writeStatus();
});
}).listen(port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment