node.js script to set all LIFX bulbs on or off, will keep on trying until 'expectedbulbs' number of lamps are in the desired state
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var lifx = require('./lifx'); | |
var util = require('util'); | |
var lx = lifx.init(); | |
var expectedbulbs = 2; | |
var target; | |
var bulbsAtTarget = []; | |
var startTime = new Date().getTime(); | |
function processBulbState(address, powerstate) { | |
var atTarget = target ? powerstate > 0 : powerstate == 0; | |
if (atTarget) regBulbAtTarget(address); | |
} | |
function regBulbAtTarget(bulbaddress) { | |
var inList = false; | |
for (var i in bulbsAtTarget) { | |
if (bulbsAtTarget[i] == bulbaddress) { | |
inList = true; | |
} | |
} | |
if (!inList) bulbsAtTarget.push(bulbaddress); | |
if (bulbsAtTarget.length == expectedbulbs) { | |
console.log("All bulbs at target after " + (new Date().getTime() - startTime)/1000 + " seconds."); | |
process.exit(0); | |
} | |
} | |
function doIt() { | |
if (target) { | |
lx.lightsOn(); | |
} else { | |
lx.lightsOff(); | |
} | |
} | |
function doItRepeatedly() { | |
console.log("+++ timeout - retrying."); | |
doIt(); | |
setTimeout(doItRepeatedly, 5000); | |
} | |
lx.on('bulb', function(b) { // this has no function | |
console.log("new bulb: ", b); | |
}); | |
lx.on('gateway', function(b) { | |
console.log('Gateway found at ' + b.ipAddress.ip + ':' + b.ipAddress.port); | |
console.log("arguments: ", process.argv); | |
target = process.argv[2] == 'on' ? true : false; | |
doIt(); | |
setTimeout(doItRepeatedly, 5000); | |
var m = packet.getPowerState(); | |
lx.sendToAll(m); | |
}); | |
lx.on('packet', function(p) { | |
switch (p.packetTypeShortName) { | |
case 'powerState': | |
console.log('*** onoff: ' + p.payload.onoff + " for " + p.preamble.bulbAddress.toString('hex')); | |
processBulbState(p.preamble.bulbAddress.toString('hex'), p.payload.onoff); | |
break; | |
default: | |
//console.log('Unknown packet.'); | |
} | |
}); | |
lx.on('bulbstate', function(b) { | |
console.log("+++ bulbstate " + b.state.power + " for " + b.bulb.lifxAddress.toString('hex')); | |
processBulbState(b.bulb.lifxAddress.toString('hex'), b.state.power); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment