Skip to content

Commit

Permalink
Add random number message
Browse files Browse the repository at this point in the history
  • Loading branch information
ragingwind committed Feb 25, 2014
1 parent 600e702 commit d4d1f14
Show file tree
Hide file tree
Showing 3 changed files with 407 additions and 11 deletions.
31 changes: 21 additions & 10 deletions mqttbot.js → lib/mqttbot.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ var nopt = require('nopt');
var path = require('path');
var fs = require('fs');
var url = require('url');
var pkg = require('./package.json');
var pkg = require('../package.json');
var _ = require('lodash');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
Expand All @@ -20,6 +20,7 @@ var opts = nopt({
bot: [Stream, Number],
interval: [Stream, Number],
prompt: Boolean,
random: [String],
help: Boolean,
version: Boolean
}, {
Expand Down Expand Up @@ -48,13 +49,15 @@ function prepare(cb) {
'Examples:',
'\tmqttbot -b 2 -t test ws://localhost:8080/mqtt',
'\tmqttbot -b 10 -t test mqtt://username:passwd@mx.cloudmqtt.com:18629\n',
'\tmqttbot -b 2 -t test -r 0 100 ws://localhost:8080/mqtt',
'Startup:',
'\t-t, --topic [string] topic to publish on',
'\t-b, --bot [int] number of bots',
'\t-i, --interval [int] timer interval in ms between publications',
'\t-p, --prompt interactive prompt, without timer',
'\t-v, --version display the version',
'\t-h, --help print this help.'
'\t-t, --topic [string] topic to publish on',
'\t-b, --bot [int] number of bots',
'\t-i, --interval [int] timer interval in ms between publications',
'\t-p, --prompt interactive prompt, without timer',
'\t-r, --random [min]-[max] random number message',
'\t-v, --version display the version',
'\t-h, --help print this help.'
].join('\n'));
}

Expand All @@ -74,8 +77,6 @@ function mqttbot(opts) {
mqttopts.password = account[1];
}

console.log(opts);

this.log('connect to', opts.url.href);

if (opts.url.protocol === "mqtt:") {
Expand Down Expand Up @@ -120,6 +121,12 @@ prepare(function () {
var recvCount = 0;
var bots = [];
var readline;
var randomNumbericMessage = function() {
var range = opts.random.split('-');
var min = parseInt(range[0], 10);
var max = parseInt(range[1], 10);
return (Math.random() * (max - min + 1) + min).toString();
}

var randomBotid = function () {
var min = 0, max = opts.bot - 1;
Expand All @@ -128,7 +135,11 @@ prepare(function () {

var sendMessage = function (message) {
var bot = bots[randomBotid()];
bot.pub(message || ['`from bot', bot.opts.botid, '` at', Date.now()].join(' '));
if (!message) {
message = opts.random ? randomNumbericMessage()
: ['`from bot', bot.opts.botid, '` at', Date.now()].join(' ');
}
bot.pub(message);
};

var showPrompt = function() {
Expand Down
Loading

0 comments on commit d4d1f14

Please sign in to comment.