-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish.js
37 lines (30 loc) · 966 Bytes
/
publish.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
"use strict";
var mqtt = require('mqtt');
var _ = require('underscore');
var client;
var topic;
var logger;
exports.init = function(options, logs) {
logger = logs;
if (! options || ! options.enable) {logger.info('publisher disabled'); return}
// setting some defaults
_.extend({
host: '127.0.0.1',
port: '1883',
topic: 'klokey',
options: {}
}, options);
client = mqtt.connect('mqtt://' + options.host + ':' + options.port, options.options);
client.on('error', function (err) {
logger.error('publisher', err.message);
}).on('connect', function () {
logger.info('publisher initialized');
});
topic = options.topic;
};
exports.publish = function(message, topicPostfix, retain) {
if (! client) {return}
if (typeof topicPostfix === 'undefined') { topicPostfix = ''; }
var options = {retain: !!retain};
client.publish(topic + topicPostfix, message, options);
};