|
var mqtt = require('mqttjs') |
|
, optimist = require('optimist'); |
|
|
|
var argv = optimist |
|
.usage('lively - a script that makes itself look alive\nnode lively.js -t <topic> -h <host> -p <port>') |
|
|
|
.options('t', { |
|
demand: true |
|
, describe: 'Topic to publish status messages on' |
|
, alias: 'topic' |
|
}) |
|
.options('h', { |
|
demand: true |
|
, describe: 'Broker to publish status messages on' |
|
, alias: 'host' |
|
}) |
|
.options('c', { |
|
demand: true |
|
, describe: 'The ID of the lively client' |
|
, alias: 'id' |
|
}) |
|
.options('k', { |
|
default: 1000 |
|
, describe: 'Keepalive period' |
|
, alias: 'keepalive' |
|
}) |
|
.options('p', { |
|
default: 1883 |
|
, describe: 'Broker port' |
|
, alias: 'port' |
|
}) |
|
.options('present', { |
|
default: '1' |
|
, describe: 'The \'present\' message to publish to the broker' |
|
}) |
|
.options('not-present', { |
|
default: '0' |
|
, describe: 'The \'not present\' message to publish to the broker' |
|
}) |
|
.argv; |
|
|
|
var host = argv.h |
|
, topic = argv.t |
|
, cid = argv.c |
|
, keepalive = argv.k |
|
, pr = argv['present'] |
|
, np = argv['not-present'] |
|
, port = argv.p; |
|
|
|
console.dir(argv); |
|
|
|
function statusPacket(status) { |
|
return { |
|
topic: topic |
|
, payload: status |
|
, retain: true |
|
} |
|
} |
|
|
|
var client = mqtt.createClient(port, host, function(err, client) { |
|
if (err) { console.log(err); process.exit(1); } |
|
client.connect({client: cid, will: statusPacket(np), keepalive: keepalive}); |
|
client.on('connack', function(packet) { |
|
if (packet.returnCode !== 0) return console.log('Bad code'); |
|
client.publish(statusPacket(pr)); |
|
}); |
|
client.on('pingresp', function(packet) { |
|
console.log('Ping resp received'); |
|
}); |
|
client.interval = setInterval(function() { |
|
client.pingreq(); |
|
}, keepalive); |
|
}); |
|
|
|
function handleSignal(signal) { |
|
process.on(signal, function() { |
|
clearInterval(client.interval); |
|
client.publish(statusPacket(np)); |
|
client.disconnect(); |
|
}); |
|
} |
|
|
|
handleSignal('SIGHUP'); |
|
handleSignal('SIGINT'); |
|
handleSignal('SIGQUIT'); |
|
handleSignal('SIGTERM'); |