forked from arvindr21/pi_livestreaming
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
72 lines (52 loc) · 1.69 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
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
var path = require('path');
var spawn = require('child_process').spawn;
var proc;
app.use('/', express.static(path.join(__dirname, 'stream')));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
var sockets = {};
io.on('connection', function(socket) {
sockets[socket.id] = socket;
console.log("Total clients connected : ", Object.keys(sockets).length);
socket.on('disconnect', function() {
delete sockets[socket.id];
// no more sockets, kill the stream
if (Object.keys(sockets).length == 0) {
app.set('watchingFile', false);
if (proc) proc.kill();
fs.unwatchFile('./stream/image_stream.jpg');
}
});
socket.on('start-stream', function() {
startStreaming(io);
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
function stopStreaming() {
if (Object.keys(sockets).length == 0) {
app.set('watchingFile', false);
if (proc) proc.kill();
fs.unwatchFile('./stream/image_stream.jpg');
}
}
function startStreaming(io) {
if (app.get('watchingFile')) {
io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
return;
}
var args = ["-w", "640", "-h", "480", "-o", "./stream/image_stream.jpg", "-t", "999999999", "-tl", "100"];
proc = spawn('raspistill', args);
console.log('Watching for changes...');
app.set('watchingFile', true);
fs.watchFile('./stream/image_stream.jpg', function(current, previous) {
io.sockets.emit('liveStream', 'image_stream.jpg?_t=' + (Math.random() * 100000));
})
}