-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalarm.js
98 lines (85 loc) · 2.35 KB
/
alarm.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
var settings = require('./settings.json');
var Client = require('uptime-robot');
var cl = new Client(settings.API_KEY);
var Gpio = require('onoff').Gpio;
// Global variables
var STATUS_MAP = {
0: 'PAUSED',
1: 'NOT_CHECKED_YET',
2: 'UP',
8: 'SEEMS_DOWN',
9: 'DOWN'
};
// alarm object
var alarm = {
start: function () {
console.log('Starting app');
this.PIN = new Gpio(settings.PIN, 'out');
this.PIN.writeSync(0);
this.PIN_CLOSED = false;
this.alarmDuration = settings.alarmDuration;
this.eventListeners();
this.check();
},
check: function () {
var self = this;
this.monitorID = parseInt(settings.monitorID, 10);
console.log('Getting monitor data');
this.getMonitors(function (data) {
data.forEach(function (monitor) {
if (monitor.id == self.monitorID) {
console.log('Monitor:', monitor.id, 'status:', STATUS_MAP[monitor.status]);
if (STATUS_MAP[monitor.status] == 'DOWN') {
// Trigger alarm
self.alarm();
}
}
});
});
},
getMonitors: function (callback) {
console.log('Fetching available monitors');
cl.getMonitors(function (error, data) {
if (error !== null) {
console.error('Error:', error);
return;
}
console.log('Available monitors:', data.length);
if (typeof callback === 'function') {
callback(data);
}
});
},
alarm: function () {
var self = this;
console.log('Triggering alarm');
self.PIN.writeSync(1);
setTimeout(function () {
console.log('Terminating app');
self.PIN.writeSync(0);
self.PIN.unexport();
self.PIN_CLOSED = true;
}, self.alarmDuration * 1000);
},
eventListeners: function () {
var self = this;
function exitHandler(options, error) {
if (options.cleanup && !self.PIN_CLOSED) {
console.log('Terminating app');
self.PIN.writeSync(0);
self.PIN.unexport();
self.PIN_CLOSED = true;
}
if (error) {
console.error(error.stack);
}
if (options.exit) {
process.exit();
}
}
process.on('exit', exitHandler.bind(null, {cleanup: true}));
process.on('SIGINT', exitHandler.bind(null, {exit: true}));
process.on('uncaughtException', exitHandler.bind(null, {exit: true}));
}
};
alarm.start();