Created
July 8, 2014 13:42
-
-
Save SirPepe/bc10271fd42aac9a387d to your computer and use it in GitHub Desktop.
Lights up an led when there's unread mail
This file contains hidden or 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
/* usage: node inbox.js -u [email protected] -p hunter2 */ | |
var Q = require('q'); | |
var minimist = require('minimist'); | |
var inbox = require('inbox'); | |
var Five = require("johnny-five"); | |
function handleError(err){ | |
console.error(err); | |
} | |
var argv = minimist(process.argv.slice(2)); | |
var imapUser = argv.u; | |
var imapPass = argv.p; | |
if(!imapUser) throw new Error('No user specified (-u option)'); | |
if(!imapPass) throw new Error('No password specified (-p option)'); | |
var imapClient = inbox.createConnection(false, 'imap.gmail.com', { | |
secureConnection: true, | |
auth: { user: imapUser, pass: imapPass } | |
}); | |
var whenImapConnected = Q.Promise(function resolver(resolve){ | |
imapClient.connect(); | |
imapClient.on('connect', function(){ | |
imapClient.openMailbox('INBOX', function(err, info){ | |
if(err) throw err; | |
resolve(imapClient); | |
}); | |
}); | |
}); | |
var board = new Five.Board(); | |
var whenHardwareReady = Q.Promise(function resolver(resolve){ | |
board.on('ready', function(){ | |
var hardware = { | |
statusLed: new Five.Led(6) | |
}; | |
resolve(hardware); | |
}); | |
}); | |
function checkForUnreadMail(interval, callback){ | |
console.info(new Date() + ': Checking for unread messages...'); | |
imapClient.search({ unseen: true }, function(err, data){ | |
if(err) throw err; | |
console.info(new Date() + ': ' + data.length + ' unread messages found'); | |
var unreadMail = (data.length > 0); | |
callback(unreadMail); | |
setTimeout(checkForUnreadMail.bind(null, interval, callback), interval); | |
}); | |
} | |
Q.all([ whenImapConnected, whenHardwareReady ]) | |
.spread(function(client, hardware){ | |
checkForUnreadMail(20000, function(unreadMail){ | |
if(unreadMail && hardware.statusLed.isOn === false){ | |
hardware.statusLed.on(); | |
} | |
else if(!unreadMail && hardware.statusLed.isOn === true){ | |
hardware.statusLed.off(); | |
} | |
}); | |
}) | |
.fail(handleError); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment