-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
102 lines (87 loc) · 2.25 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
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
99
100
101
102
const bridgePort = 8123
const http = require('http')
const logger = require('./utils/logger')
const USB = require('./utils/usb')
const commands = require('./constants/projector')
let USBInterface;
logger.log('node.js version: ' + process.version)
http.createServer(handleRequest).listen(bridgePort, (err) => {
if (err) logger.error(err)
else {
logger.info(`server is now running on port ${bridgePort}!`)
USBInterface = new USB();
}
})
function handleRequest(req, res){
const command = req.headers['req-command']
logger.log(`received request for command: '${command}'`)
switch(command) {
case 'getStatus':
getProjectorStatus(res)
break
case 'getLampHours':
getLampHours(res)
break
case 'turnOn':
toggleProjector(true, req, res)
break
case 'turnOff':
toggleProjector(false, req, res)
break
default:
res.end()
logger.error(`request for invalid command`)
}
}
/**
* Returns the power status of the projector.
*/
function getProjectorStatus(res) {
USBInterface.sendCommand(commands.STATUS)
.then((value) => {
const pwrStatus = { projector: { state: value }}
logger.log(`projector status: ${value}`)
res.setHeader('res-command', JSON.stringify(pwrStatus))
res.end()
})
.catch((err) => {
logger.error(err)
res.setHeader('res-command', 'failure')
res.end()
})
}
/**
* Returns the total lamp hours of projector bulb.
*/
function getLampHours(res) {
USBInterface.sendCommand(commands.LAMP_HOURS)
.then((value) => {
const lampHours = { projector: { lamp_hours: value }}
logger.log(`lamp hours: ${value}`)
res.setHeader('res-command', JSON.stringify(lampHours))
res.end()
})
.catch((err) => {
logger.error(err)
res.setHeader('res-command', 'failure')
res.end()
})
}
/**
* Send command to turn on/off projector.
*/
function toggleProjector(turnOn, req, res) {
const actualCmd = turnOn ? commands.ON : commands.OFF
const nextState = turnOn ? 1 : 0
USBInterface.sendCommand(actualCmd)
.then(() => {
logger.log(`projector on? ${!!nextState}`)
res.setHeader('res-command', 'success')
res.end()
})
.catch((err) => {
logger.error(err)
res.setHeader('res-command', 'failure')
res.end()
})
}