-
Notifications
You must be signed in to change notification settings - Fork 1
/
mqtt.js
59 lines (53 loc) · 1.5 KB
/
mqtt.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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
var mqtt = require('mqtt');
var fs = require('fs');
var env = require('./env');
var Promise = require('promise');
var clientOptions = {
protocol: 'mqtts',
host: env.mqtt.host,
port: env.mqtt.port,
username: env.mqtt.username,
password: env.mqtt.password,
ca: [fs.readFileSync('./certificates/ca.crt')],
rejectUnauthorized: true,
};
var publishOptions = {
qos: 2,
};
function log() {
if (false) {
console.log.apply(console, arguments);
}
}
module.exports.send = function(topic, payload) {
return new Promise(function(resolve, reject) {
if (!topic) {
reject('No topic specified.');
return;
}
if (typeof payload !== 'string' && typeof payload !== 'undefined') {
reject('Payload must be a string or undefined.');
return;
}
log('Attempting connection...');
var client = mqtt.connect(clientOptions);
client.on('connect', function() {
log('Connected.');
log('Attempting publish...');
client.publish(topic, payload, publishOptions, function(e) {
if (e) {
log('Publishing error.', e);
reject(e);
}
log('Published.');
client.end();
resolve();
});
});
client.on('error', function(e) {
log('Connection error.', e);
client.end();
reject(e);
});
});
};