-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwebserver.js
More file actions
70 lines (55 loc) · 1.85 KB
/
webserver.js
File metadata and controls
70 lines (55 loc) · 1.85 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
#!/usr/bin/env node
'use strict';
// Default port for this server is 8080, or DOORBELL_PORT env variable.
// The default is overridable with -p/--port.
if(process.env.DOORBELL_PORT) {
console.log(`DOORBELL_PORT set from env variable: ${process.env.DOORBELL_PORT}`)
}
const port = process.env.DOORBELL_PORT || 8080;
const { ArgumentParser } = require('argparse');
const { version } = require('./package.json');
const parser = new ArgumentParser({
description: 'Argparse functionality'
});
parser.add_argument('-p', '--port', { help: 'Define port for web server' });
let args = parser.parse_args();
if(args.port && !process.env.DOORBELL_PORT) port = parseInt(args.port);
var express = require('express');
var app = express();
var server = app.listen(port);
var io = require('socket.io')(server);
var path = require('path');
var fs = require('fs')
const dirPath = path.join(__dirname, '/public');
app.use(express.static(dirPath));
console.log(`Server running on port ${port}`);
var state = "green";
app.get('/', function(req, res){
res.sendFile(__dirname + '/public/index.html');
});
io.on('connection', function (socket) {
socket.on('init', function(){
if(state==="red"){
io.emit('init');
socket.broadcast.emit('init');
}
})
socket.on('check', function(value) {
if (state === "green" && value === 1) {
//console.log("change:" + value);
state = "red";
fs.readdir(dirPath + "/audio", function(err, files){
let randomSound = files[Math.floor(Math.random() * files.length)];
//console.log(randomSound);
io.emit('change', 0, randomSound);
socket.broadcast.emit('change', 0, randomSound);
setTimeout(function(){
state = "green";
//console.log(state);
io.emit('change', 1);
socket.broadcast.emit('change', 1);
}, 10000);
});
}
});
});