-
Notifications
You must be signed in to change notification settings - Fork 1
/
subscriber.js
81 lines (65 loc) · 1.7 KB
/
subscriber.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/* Magic Mirror
* Module: MMM-MQTT
*
* By jupadin
* MIT Licensed.
*/
const Log = require('../../js/logger');
const mqtt = require('mqtt');
const Subscriber = function(url, port, auth, topics) {
let client = null;
let onConnectCallback = function () {};
let onMessageCallback = function () {};
let onErrorCallback = function () {};
this.connect = function() {
const options = {
port: port,
};
if (auth) {
options.user = auth.user;
options.password = auth.password;
}
// Connect to broker.
client = mqtt.connect(url, options);
// Subscribe to topics.
client.subscribe(topics);
// Callback functions
client.on("connect", onConnectCallback);
client.on("message", onMessageCallback);
client.on("error", onErrorCallback);
};
this.onConnect = function(callback) {
onConnectCallback = callback;
}
this.onMessage = function(callback) {
onMessageCallback = callback;
}
this.onError = function(callback) {
onErrorCallback = callback;
}
/**
* Returns the url of this subscriber.
*
* @returns {string} The url of this subscriber.
*/
this.url = function() {
return url;
};
/**
* Returns the client of this subscriber.
*
* @returns The client of this subscriber.
*/
this.client = function() {
return client;
}
/**
* Returns the topics this subscriber is subscribed to.
*
* @returns The topics this subscriber is subscribed to.
*/
this.topics = function() {
return topics;
}
};
module.exports = Subscriber;