Created
June 24, 2015 04:35
-
-
Save mmaelzer/de47abca856baf0456a8 to your computer and use it in GitHub Desktop.
image polling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** =========================== SERVER =================================== */ | |
var express = require('express'); | |
var MjpegCamera = require('mjpeg-camera'); | |
var app = express(); | |
// Create an MjpegCamera instance | |
var camera = new MjpegCamera({ | |
name: 'backdoor', | |
url: 'http://192.168.7.1/video' | |
}); | |
// Start streaming | |
camera.start(); | |
app.get('/frame', function(req, res) { | |
res.set('Content-Type', 'image/jpeg'); | |
res.status(200).send(camera.frame); | |
}); | |
app.listen(3000); | |
/** =========================== BROWSER =================================== */ | |
function startImageFeed(imageUrl, id) { | |
var img = document.getElementById(id); | |
var stop = false; | |
(function setSrc() { | |
if (stop) return; | |
img.src = imageUrl; | |
})(); | |
img.onload = setSrc; | |
img.onerror = setSrc; | |
return function() { | |
stop = true; | |
}; | |
}; | |
var stop = startImageFeed('/frame', 'video-image'); | |
// Stop "video" feed after 30 seconds | |
setTimeout(stop, 30000); |
This code is untested, but the approach should work.
class Streamer {
constructor(cameraOptions, opt_stopAfterMinutes) {
this.camera = new MjpegCamera(cameraOptions);
this.stopAfter = (opt_stopAfterMinutes || 5) * 60 * 1000; // hold in ms
this.timeout = null;
}
getFrame() {
clearTimeout(this.timeout);
return new Promise((resolve, reject) => {
if (this.camera.connection) {
resolve(this.camera.frame);
} else {
this.camera.start()
this.camera.once('data', (frame) => { resolve(frame); });
this.camera.once('error', (err) => { reject(err); });
}
this.timeout = setTimeout(() => { this.camera.stop(); }, this.stopAfter);
});
}
}
const streamer = new Streamer(cameraOptions, 5 /** Stop after 5 minutes of streaming if no new requests come in */);
app.get('/frame', function(req, res) {
streamer.getFrame()
.then(frame => {
res.set('Content-Type', 'image/jpeg');
res.status(200).send(frame);
})
.catch(err => {
res.set('Content-Type', 'text/plain');
res.status(500).send(err.toString());
});
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, Friend!
How it can be scale for many cameras app.get ('/ frame / CameraID')
Start stream only when requested and stop after N minutes