Skip to content

Commit

Permalink
Created camserver
Browse files Browse the repository at this point in the history
  • Loading branch information
jungkumseok committed Oct 22, 2016
0 parents commit a54dc49
Show file tree
Hide file tree
Showing 6 changed files with 202 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.project
.pydevproject
__pycache__/
29 changes: 29 additions & 0 deletions camera.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import cv2, time, base64
import threading

class WebCam(threading.Thread):
def __init__(self, framerate):
threading.Thread.__init__(self)
self.framerate = framerate
self.camera = cv2.VideoCapture(-1)
self.raw_image = None
self.image = None

def update_frame(self):
success, self.raw_image = self.camera.read()
ret, self.image = cv2.imencode('.jpg', self.raw_image)

@property
def data(self):
return base64.b64encode(self.image.tostring())

def start_stream(self):
last_updated = time.time()
while True:
curtime = time.time()
if (curtime - last_updated) > (1 / self.framerate):
last_updated = curtime
self.update_frame()

def run(self):
self.start_stream()
45 changes: 45 additions & 0 deletions start.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import os, sys
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.httpserver
from camera import WebCam

settings = {
"static_path": os.path.join(os.path.dirname(__file__), "static"),
}

webcam = WebCam(15)

class WSHandler(tornado.websocket.WebSocketHandler):
def check_origin(self, origin):
return True

def open(self):
print("Websocket Connected from "+self.request.remote_ip);

def on_message(self, message):
self.write_message(webcam.data)

def on_close(self):
print("Websocket Closed")

def make_app():
return tornado.web.Application([ (r'/webcam', WSHandler),
(r'/(.*)', tornado.web.StaticFileHandler, {'path': settings['static_path'], 'default_filename': 'index.html'}),
])

def start(port):
app = make_app()
app.listen(port)
print("WebCam Service Start...")
tornado.ioloop.IOLoop.current().start()

if __name__ == "__main__":
webcam.start()
port = 8100
if len(sys.argv) > 1:
port = int(sys.argv[1])
start(port)
webcam.shutdown()
webcam.join()
15 changes: 15 additions & 0 deletions static/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

var webcamApp = angular.module('webcamApp', [])
.factory('WebCamService', function(){
var _WS = new PersistentWebSocket(window.location.hostname+':8100/webcam');
return _WS;
})
.controller('WebCamCtrl', function($scope, WebCamService){
var self = this;
self.data = undefined;
WebCamService.addEventListener('onMessageReceiveRaw', function(evt, data){
self.data = "data:image/jpg;base64,"+data;
$scope.$apply();
});
})
33 changes: 33 additions & 0 deletions static/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<title>Live WebCam Stream</title>
<meta name="description" content="live webcam stream">
<meta name="author" content="jungkumseok">
<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="">
<!--[if lt IE 9]>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
<link rel="shortcut icon" href="">

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.js"></script>

<script src="utils.js"></script>
<script src="app.js"></script>

</head>
<body ng-app="webcamApp">
<h4>Live WebCam Stream</h4>
<div ng-controller="WebCamCtrl as vm">
<img ng-src="{{vm.data}}" style="width: 600px; height: 480px;">
</div>

</body>
</html>
77 changes: 77 additions & 0 deletions static/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
'use strict';

function PersistentWebSocket(endpoint, refresh_rate, retry_rate){
var self = this;
console.log("Persistent WebSocket Object Created...");

if (!refresh_rate) refresh_rate = 100;
if (!retry_rate) retry_rate = 5000;
self.refresh_rate = refresh_rate;
self.retry_rate = retry_rate;

self.endpoint = endpoint;
self.ws_timer = null;
self.retry_timer = null;
self.socket = null;

self.ENDPOINT_ALIVE = false;

self.onMessageReceive = [];
self.onMessageReceiveRaw = [];

self.initialize();
}
PersistentWebSocket.prototype.initialize =function(){
var self = this;
if (self.socket) self.socket = null;
self.socket = new WebSocket("ws://"+self.endpoint);
self.socket.onopen = function(){
console.debug("WebSocket to "+self.endpoint+" opened");
self.ENDPOINT_ALIVE = true;
self.ws_timer = setInterval(function(){
if (self.socket.readyState == 1){
self.socket.send( JSON.stringify({ operation: 'get' }));
}
else {
clearInterval(self.ws_timer);
}
}, self.refresh_rate);
};
self.socket.onclose = function(){
self.ENDPOINT_ALIVE = false;
console.debug("WebSocket to "+self.endpoint+" closed");
clearInterval(self.ws_timer);
setTimeout(function(){
console.debug("Trying to open Websocket to "+self.endpoint+" again");
self.initialize();
}, self.retry_rate);
};
self.socket.onerror = function(){
self.ENDPOINT_ALIVE = false;
console.error("ERROR on WebSocket to "+self.endpoint);
};
self.socket.onmessage = function(event){
for (var i=0; i < self.onMessageReceive.length; i++){
self.onMessageReceive[i](event, JSON.parse(event.data));
}
for (var i=0; i < self.onMessageReceiveRaw.length; i++){
self.onMessageReceiveRaw[i](event, event.data);
}
};
};
PersistentWebSocket.prototype.isAlive = function(){
return this.ENDPOINT_ALIVE;
}
PersistentWebSocket.prototype.addEventListener = function(eventName, handlerFunc){
console.log("Binding to Event "+eventName);
if (this[eventName].indexOf(handlerFunc) < 0) this[eventName].push(handlerFunc);
else throw "No Such Event : "+eventName;
}
PersistentWebSocket.prototype.send = function(data){
if (this.socket.readyState === 1){
this.socket.send( JSON.stringify( data ) );
}
else {
throw "Socket Not Ready";
}
};

0 comments on commit a54dc49

Please sign in to comment.