-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathnode_helper.js
More file actions
74 lines (57 loc) · 2.24 KB
/
Copy pathnode_helper.js
File metadata and controls
74 lines (57 loc) · 2.24 KB
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
var mqtt = require('mqtt');
var NodeHelper = require("node_helper");
var topics = [];
module.exports = NodeHelper.create({
start: function () {
console.log('Starting node helper for: ' + this.name);
this.loaded = false;
},
socketNotificationReceived: function (notification, payload) {
var self = this;
console.log(self.name + ': Received notification from socket of type ' + notification);
if (notification === 'MQTT_CONFIG') {
self.config = payload;
// Read topics to subscribe to from the subscriptions list
for (i = 0; i < self.config.subscriptions.length; i++) {
topics[i] = self.config.subscriptions[i].topic;
}
self.loaded = true;
self.options = {};
if (self.config.mqttServer.user) self.options.username = self.config.mqttServer.user;
if (self.config.mqttServer.password) self.options.password = self.config.mqttServer.password;
var server = (self.config.mqttServer.url.match(/^mqtts?:\/\//) ? '' : 'mqtt://') + self.config.mqttServer.url;
console.log(self.name + ': Connecting to ' + server);
self.client = mqtt.connect(server, self.options);
// console.log(self.name + ': Result of client after MQTT connection attempt is ' + String(self.client));
self.client.on('error', function (err) {
console.log(self.name + ': Error: ' + String(err));
});
self.client.on('reconnect', function (err) {
self.value = 'reconnecting';
});
self.client.on('offline', function (err) {
console.log(self.name + ' Client has gone offline from broker');
});
self.client.on('connect', function (connack) {
console.log(self.name + ' connected to ' + self.config.mqttServer.url);
console.log(self.name + ': subscribing to ' + topics);
self.client.subscribe(topics, function(err) {
if (err) {
console.log(self.name + ' Failed to subscribe to topics: ' + String(err) )
}
});
});
self.client.on('message', function (topic, payload) {
// Only pass on messages in a topic that we know about
console.log(self.name + ': Received MQTT message from topic ' + topic);
if (topics.includes(topic)) {
var value = payload.toString();
self.sendSocketNotification('MQTT_PAYLOAD', {
topic: topic,
value: value
});
}
});
}
},
});