forked from javiergayala/MMM-mqtt
-
Notifications
You must be signed in to change notification settings - Fork 3
/
node_helper.js
71 lines (61 loc) · 1.96 KB
/
node_helper.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
'use strict';
/* Magic Mirror
* Module: MMM-IndoorTemp
*
* By Sebastian Hodapp https://www.sebastian-hodapp.de,
*
* based on Javier Ayala's module MMM-mqtt http://www.javierayala.com/
* MIT Licensed.
*/
const NodeHelper = require('node_helper');
var mqtt = require('mqtt');
module.exports = NodeHelper.create({
start: function() {
console.log('MMM-IndoorTemp started ...');
this.clients = [];
},
connectMqtt: function(config) {
var self = this;
var client;
if(typeof self.clients[config.mqttServer] === "undefined") {
console.log("Creating new MQTT client for url: ", config.mqttServer);
client = mqtt.connect(config.mqttServer);
self.clients[config.mqttServer] = client;
client.on('error', function(error) {
console.log('*** MQTT JS ERROR ***: ' + error);
self.sendSocketNotification('ERROR', {
type: 'notification',
title: 'MQTT Error',
message: 'The MQTT Client has suffered an error: ' + error
});
});
client.on('offline', function() {
console.log('*** MQTT Client Offline ***');
self.sendSocketNotification('ERROR', {
type: 'notification',
title: 'MQTT Offline',
message: 'MQTT Server is offline.'
});
client.end();
});
} else {
client = self.clients[config.mqttServer];
}
if(config.mode !== 'send') {
client.subscribe(config.topic);
client.on('message', function(topic, message) {
self.sendSocketNotification('MQTT_DATA', {'topic':topic, 'data':message.toString()});
});
}
},
socketNotificationReceived: function(notification, payload) {
if (notification === 'MQTT_SERVER') {
this.connectMqtt(payload);
} else if(notification == 'MQTT_SEND') {
var client = this.clients[payload.mqttServer];
if(typeof client !== "undefined") {
client.publish(payload.topic, JSON.stringify(payload.payload));
}
}
}
});