-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathgarage.js
More file actions
90 lines (77 loc) · 1.97 KB
/
garage.js
File metadata and controls
90 lines (77 loc) · 1.97 KB
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
// garage.js
const mqtt = require('mqtt')
const client = mqtt.connect('mqtt://broker.hivemq.com')
/**
* The state of the garage, defaults to closed
* Possible states : closed, opening, open, closing
*/
var state = 'closed'
client.on('connect', () => {
client.subscribe('garage/open')
client.subscribe('garage/close')
// Inform controllers that garage is connected
client.publish('garage/connected', 'true')
sendStateUpdate()
})
client.on('message', (topic, message) => {
console.log('received message %s %s', topic, message)
switch (topic) {
case 'garage/open':
return handleOpenRequest(message)
case 'garage/close':
return handleCloseRequest(message)
}
})
function sendStateUpdate () {
console.log('sending state %s', state)
client.publish('garage/state', state)
}
function handleOpenRequest (message) {
if (state !== 'open' && state !== 'opening') {
console.log('opening garage door')
state = 'opening'
sendStateUpdate()
// simulate door open after 5 seconds (would be listening to hardware)
setTimeout(() => {
state = 'open'
sendStateUpdate()
}, 5000)
}
}
function handleCloseRequest (message) {
if (state !== 'closed' && state !== 'closing') {
state = 'closing'
sendStateUpdate()
// simulate door closed after 5 seconds (would be listening to hardware)
setTimeout(() => {
state = 'closed'
sendStateUpdate()
}, 5000)
}
}
/**
* Want to notify controller that garage is disconnected before shutting down
*/
function handleAppExit (options, err) {
if (err) {
console.log(err.stack)
}
if (options.cleanup) {
client.publish('garage/connected', 'false')
}
if (options.exit) {
process.exit()
}
}
/**
* Handle the different ways an application can shutdown
*/
process.on('exit', handleAppExit.bind(null, {
cleanup: true
}))
process.on('SIGINT', handleAppExit.bind(null, {
exit: true
}))
process.on('uncaughtException', handleAppExit.bind(null, {
exit: true
}))