-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathcontroller.js
More file actions
61 lines (51 loc) · 1.46 KB
/
controller.js
File metadata and controls
61 lines (51 loc) · 1.46 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
// controller.js
const mqtt = require('mqtt')
const client = mqtt.connect('mqtt://broker.hivemq.com')
var garageState = ''
var connected = false
client.on('connect', () => {
client.subscribe('garage/connected')
client.subscribe('garage/state')
})
client.on('message', (topic, message) => {
switch (topic) {
case 'garage/connected':
return handleGarageConnected(message)
case 'garage/state':
return handleGarageState(message)
}
console.log('No handler for topic %s', topic)
})
function handleGarageConnected (message) {
console.log('garage connected status %s', message)
connected = (message.toString() === 'true')
}
function handleGarageState (message) {
garageState = message
console.log('garage state update to %s', message)
}
function openGarageDoor () {
// can only open door if we're connected to mqtt and door isn't already open
if (connected && garageState !== 'open') {
// Ask the door to open
client.publish('garage/open', 'true')
}
}
function closeGarageDoor () {
// can only close door if we're connected to mqtt and door isn't already closed
if (connected && garageState !== 'closed') {
// Ask the door to close
client.publish('garage/close', 'true')
}
}
// --- For Demo Purposes Only ----//
// simulate opening garage door
setTimeout(() => {
console.log('open door')
openGarageDoor()
}, 5000)
// simulate closing garage door
setTimeout(() => {
console.log('close door')
closeGarageDoor()
}, 20000)