-
Notifications
You must be signed in to change notification settings - Fork 3
/
node_helper.js
100 lines (77 loc) · 2.85 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* Magic Mirror
* Node Helper for module: mmm-toggle-by-mqtt
* Repository URL: https://github.com/moejetz/mmm-toggle-by-mqtt
*
* By Moritz Kraus
* MIT Licensed.
*/
var NodeHelper = require('node_helper');
var mqtt = require('mqtt');
var { exec } = require('child_process');
module.exports = NodeHelper.create({
isMqttListenerStarted: false,
config: {},
// Used for initialisation. Read and set config overrides, then start mqtt listener as singleton.
socketNotificationReceived: function(notification, payload) {
console.log(this.name + ': received a socket notification. Key: ' + notification + ' - payload:', payload);
this.config = payload;
if(notification !== this.config.socketNotificationKey) {
console.log(this.name + ': wrong socket communication key. Ignoring...');
return;
}
if(this.isMqttListenerStarted) {
console.log(this.name + ': ignoring new config data because the mqtt listener has already been started.');
} else {
this.startMqttListener();
}
},
// Start mqtt client and register listener
startMqttListener: function () {
var self = this;
var host = '';
if(self.config.mqttHost.includes('mqtt://')) {
host = self.config.mqttHost;
} else {
host = 'mqtt://' + self.config.mqttHost;
}
var options = {};
if (self.config.mqttUsername) {
options.username = self.config.mqttUsername;
}
if (self.config.mqttPassword) {
options.password = self.config.mqttPassword;
}
var client = mqtt.connect(host, options);
client.on('connect', function () {
console.log('Connected to ' + self.config.mqttHost);
client.subscribe(self.config.mqttTopic);
});
client.on('message', function (topic, message) {
message = message + '';
if(topic===self.config.mqttTopic) {
if(message==='on') {
self.turnDisplayOn();
} else if(message==='off') {
self.turnDisplayOff();
} else {
self.publishState(self, message, topic);
}
}
});
client.on('error', function (error) {
console.error(self.name + ' ' + error);
});
},
// Publish state to module (mmm-toggle-by-presence.js)
publishState: function(self, command, topic) {
self.sendSocketNotification(this.config.socketNotificationKey, {command: command, topic: topic});
},
// Turn display (hdmi) on
turnDisplayOn: function() {
exec('vcgencmd display_power 1 >/dev/null 2>&1');
},
// Turn display (hdmi) off
turnDisplayOff: function() {
exec('vcgencmd display_power 0 >/dev/null 2>&1');
}
});