-
Notifications
You must be signed in to change notification settings - Fork 0
/
mqtt.js
55 lines (45 loc) · 1.39 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
const mqtt = require('mqtt');
const { log } = require('./logger');
let mqttClient;
module.exports = {
connect: connect,
subscribe: subscribe,
publish: publish
}
function connect(server, username, password) {
const mqttOptions = { host: server };
if (username && password) {
mqttOptions.username = username;
mqttOptions.password = password;
}
mqttClient = mqtt.connect(mqttOptions);
}
/**
* setup subscription to a topic
* @param {string} topic
* @param {function} callbackFn
*/
function subscribe(topic, callbackFn){
if (typeof topic === 'undefined' || topic.length === 0) {
throw new Error('Topic required');
} else if (typeof callbackFn !== 'function') {
throw new Error('Callback function required for new message received');
}
log(`Subscribing to '${topic}'`, true);
mqttClient.subscribe(topic, function (err) {
log(`Subscribed to '${topic}'`, true);
if (err){
throw new Error(err);
}
});
mqttClient.on('message', callbackFn);
}
function publish(topic, message) {
if (typeof topic === 'undefined' || topic.length === 0) {
throw new Error('Topic required');
} else if (typeof message === 'undefined') {
throw new Error('Message required');
}
log(`Publish '${topic}' message '${message}'`, true);
mqttClient.publish(topic, message);
}