-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
65 lines (53 loc) · 1.59 KB
/
Copy pathindex.js
File metadata and controls
65 lines (53 loc) · 1.59 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
'use strict'
const http = require('http')
const ip = require('ip')
const sqlite3 = require('sqlite3')
const onServerDeath = require('death')
const db = require('./classes/db')
const DB = new db()
const CONFIG = require('./config')
const led = require('./classes/led')
const LED = new led()
// If DB does not exist, create it.
// TODO: die if fail
console.log('creating DB', DB.createIfNotExists())
// TODO: move all of this out into a config file
const port = CONFIG.PORT
const resetPort = CONFIG.RESET_PORT
console.log(`Local IP: ${ip.address()}`)
console.log(`Listening on: ${port}`)
http.createServer((req, res) => {
// favicon.ico is requested automatically as a second request. Capture it here
if (req.url ==='/favicon.ico') {
res.writeHead(200, {'Content-Type': 'image/x-icon'} )
res.end()
return
}
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Web access hit. Light is probably going')
console.log(`Connection received at: ${humanReadableDate()}`)
LED.run()
const insertResult = DB.insertIp(req.connection.remoteAddress)
console.log('Insert to DB', insertResult)
}).listen(port)
if (resetPort) {
console.log(`Reset running on: ${resetPort}`)
http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Reset')
LED.endBlink()
}).listen(resetPort)
}
function humanReadableDate () {
const now = new Date
return now.toISOString().replace('T', ' ').substr(0, 19)
}
onServerDeath(function(signal, err) {
LED.destroy()
if (signal) {
console.log(signal)
} else {
console.log(err)
}
DB.close()
})