-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (58 loc) · 1.98 KB
/
index.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
var mqtt = require('mqtt');
var exec = require('child_process').exec;
var myLog = function(lbl, vars) {
if (verbose) console.log(lbl, vars);
}
// check for command line arguments
var args = process.argv.slice(2);
var opts = {};
for(var i = 0; i < args.length; i++) {
if(args[i].indexOf('=') > 0) {
var parts = args[i].split('=');
opts[parts[0]] = parts[1];
}
}
myLog('Command parameters: ', opts);
var verbose = (opts.verbose) ? true : false;
var url = 'tcp://';
if (opts.username && opts.password) {
url += opts.username + ':' + opts.password + '@';
}
url += (opts.host) ? opts.host : 'localhost';
myLog('MQTT subscriber connecting: ', url);
var client = mqtt.connect(url);
var sref = null;
var namespace = opts.namespace || 'namespace';
var playerId = opts.playerId || 'player01';
client.on('connect', function () {
myLog('MQTT subscriber connected: ', url);
var topicSubscription = namespace + '/' + playerId + '/#';
myLog('MQTT subscribe to: ', topicSubscription);
client.subscribe(topicSubscription);
client.publish(namespace + '/' + playerId + '/status', 'started');
});
client.on('message', function (topic, message) {
var action = topic.toString().split('/').pop();
myLog('MQTT subscriber action: ', action);
var payload = message.toString();
myLog('MQTT subscriber payload: ', payload);
switch (action) {
case 'reboot':
client.publish(namespace + '/' + playerId + '/status', 'rebooting');
exec('sudo /sbin/shutdown -r now');
break;
case 'shutdown':
client.publish(namespace + '/' + playerId + '/status', 'shutting down');
exec('sudo /sbin/shutdown now');
break;
case 'cec-power':
if(message === 'on') {
client.publish(namespace + '/' + playerId + '/status', 'cec-power-on');
exec('echo "on 0" | sudo cec-client -s -d 1');
} else {
client.publish(namespace + '/' + playerId + '/status', 'cec-power-off');
exec('echo "standby 0" | sudo cec-client -s -d 1');
}
break;
}
});