-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
84 lines (80 loc) · 2.21 KB
/
index.js
File metadata and controls
84 lines (80 loc) · 2.21 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
var http = require("http"),
url = require('url'),
fs = require('fs'),
mime = require('mime'),
io = require('socket.io')(http),
Gpio = require('pigpio').Gpio,
pir = new Gpio(17, {
mode: Gpio.INPUT,
alert: true
}),
action = false,
clients = 0,
timeout;
var server = http.createServer(function(request, response) {
var path = url.parse(request.url).pathname;
switch (path) {
case '/':
path = '/index.html';
default:
fs.readFile(__dirname + '/www' + path, function(error, data) {
if (error) {
response.writeHead(404);
response.write("opps this doesn't exist - 404");
} else {
response.writeHead(200, {
"Content-Type": mime.getType(path)
});
response.write(data, "utf8");
}
response.end();
});
}
});
server.listen(8000);
console.log('server init @8000');
io.listen(server);
io.on('connection', function(client) {
clients++;
console.log('new client');
console.log('clients', clients);
console.log('client emit action', action);
client.emit('action', action);
client.on('disconnect', function() {
clients--;
if (!clients) {
clearTimeout(timeout);
timeout = 0;
}
console.log('clients', clients);
});
});
pir.on('alert', function(level, tick) {
console.log('alert', level);
if (timeout) {
clearTimeout(timeout);
timeout = 0;
}
if (level === 1) {
if (!clients) {
console.log('No clients!');
return;
}
if (action) {
return;
}
console.log('sockets emit action', action);
action = true;
console.log('sockets emit action', action);
io.sockets.emit('action', action);
} else {
if (!clients || timeout) {
return;
}
timeout = setTimeout(function () {
action = false;
console.log('sockets emit action', action);
io.sockets.emit('action', action);
}, 5000);
}
});