-
Notifications
You must be signed in to change notification settings - Fork 0
/
openhab_handler.js
74 lines (67 loc) · 1.52 KB
/
openhab_handler.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
require('log-timestamp')(function() { return '[' + new Date().toISOString() + '] %s' });
const mqtt = require('mqtt')
const { exec } = require("child_process");
const client = mqtt.connect('mqtt://localhost')
var commandTopic = 'cmnd/system'
client.on('connect', () => {
console.log("Connected to broker. Waiting for messages");
client.subscribe(commandTopic)
})
client.on('message', (topic, message) => {
console.log(topic);
if(topic == commandTopic)
return handleSystemCommand(message)
})
function handleSystemCommand(message)
{
if(message == 'system')
{
console.log("Restart System")
exec("sudo halt -p", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
}
else if(message == 'openhab')
{
console.log("Restart Open")
exec("docker restart openhab", (error, stdout, stderr) => {
if (error) {
console.log(`error: ${error.message}`);
return;
}
if (stderr) {
console.log(`stderr: ${stderr}`);
return;
}
console.log(`stdout: ${stdout}`);
});
}
}
function handleAppExit (options, err) {
if (err) {
console.log(err.stack)
}
if (options.exit) {
process.exit()
}
}
/**
* Handle the different ways an application can shutdown
*/
process.on('exit', handleAppExit.bind(null, {
exit: true
}))
process.on('SIGINT', handleAppExit.bind(null, {
exit: true
}))
process.on('uncaughtException', handleAppExit.bind(null, {
exit: true
}))