-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpiremote_server.py
216 lines (189 loc) · 7.46 KB
/
rpiremote_server.py
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
#!/usr/bin/env python
# RS_Server.py - Web Server Class for the Raspberry Pi
#
# Based on server.py from pistreaming
# ref: https://github.com/waveform80/pistreaming
# Copyright 2014 Dave Hughes <[email protected]>
#
# 06 March 2017 - 1.0 Original Issue
#
# Reefwing Software
# Simplified BSD Licence - see bottom of file.
import sys, io, os, shutil, picamera, signal
from subprocess import Popen, PIPE, check_output
from string import Template
from struct import Struct
from threading import Thread
from time import sleep, time
from http.server import HTTPServer, BaseHTTPRequestHandler
from wsgiref.simple_server import make_server
from ws4py.websocket import WebSocket
from ws4py.server.wsgirefserver import WSGIServer, WebSocketWSGIRequestHandler
from ws4py.server.wsgiutils import WebSocketWSGIApplication
###########################################
# CONFIGURATION
WIDTH = 640
HEIGHT = 480
FRAMERATE = 24
HTTP_PORT = 8082
WS_PORT = 8084
COLOR = u'#444'
BGCOLOR = u'#333'
JSMPEG_MAGIC = b'jsmp'
JSMPEG_HEADER = Struct('>4sHH')
###########################################
class StreamingHttpHandler(BaseHTTPRequestHandler):
def do_HEAD(self):
self.do_GET()
def do_GET(self):
if self.path == '/':
self.send_response(301)
self.send_header('Location', '/index.html')
self.end_headers()
return
elif self.path == '/jsmpg.js':
content_type = 'application/javascript'
content = self.server.jsmpg_content
elif self.path == '/index.html':
content_type = 'text/html; charset=utf-8'
tpl = Template(self.server.index_template)
content = tpl.safe_substitute(dict(
ADDRESS='%s:%d' % (self.request.getsockname()[0], WS_PORT),
WIDTH=WIDTH, HEIGHT=HEIGHT, COLOR=COLOR, BGCOLOR=BGCOLOR))
else:
self.send_error(404, 'File not found')
return
content = content.encode('utf-8')
self.send_response(200)
self.send_header('Content-Type', content_type)
self.send_header('Content-Length', len(content))
self.send_header('Last-Modified', self.date_time_string(time()))
self.end_headers()
if self.command == 'GET':
self.wfile.write(content)
class StreamingHttpServer(HTTPServer):
def __init__(self):
super(StreamingHttpServer, self).__init__(
('', HTTP_PORT), StreamingHttpHandler)
with io.open('index.html', 'r') as f:
self.index_template = f.read()
with io.open('jsmpg.js', 'r') as f:
self.jsmpg_content = f.read()
class StreamingWebSocket(WebSocket):
def opened(self):
self.send(JSMPEG_HEADER.pack(JSMPEG_MAGIC, WIDTH, HEIGHT), binary=True)
class BroadcastOutput(object):
def __init__(self, camera):
print('Spawning background conversion process')
self.converter = Popen([
'avconv',
'-f', 'rawvideo',
'-pix_fmt', 'yuv420p',
'-s', '%dx%d' % camera.resolution,
'-r', str(float(camera.framerate)),
'-i', '-',
'-f', 'mpeg1video',
'-b', '800k',
'-r', str(float(camera.framerate)),
'-'],
stdin=PIPE, stdout=PIPE, stderr=io.open(os.devnull, 'wb'),
shell=False, close_fds=True)
def write(self, b):
self.converter.stdin.write(b)
def flush(self):
print('Waiting for background conversion process to exit')
self.converter.stdin.close()
self.converter.wait()
class BroadcastThread(Thread):
def __init__(self, converter, websocket_server):
super(BroadcastThread, self).__init__()
self.converter = converter
self.websocket_server = websocket_server
def run(self):
try:
while True:
buf = self.converter.stdout.read(512)
if buf:
self.websocket_server.manager.broadcast(buf, binary=True)
elif self.converter.poll() is not None:
break
finally:
self.converter.stdout.close()
class Server():
def __init__(self):
# Create a new server instance
print("Initializing camera")
self.camera = picamera.PiCamera()
self.camera.resolution = (WIDTH, HEIGHT)
self.camera.framerate = FRAMERATE
# hflip and vflip depends on how you mount the camera
self.camera.vflip = True
self.camera.hflip = False
sleep(1) # camera warm-up time
print("Camera ready")
def __str__(self):
# Return string representation of server
ip_addr = check_output(['hostname', '-I']).decode().strip()
return "Server video stream at http://{}:{}".format(ip_addr, HTTP_PORT)
def start(self):
# Start video server streaming
print('Initializing websockets server on port %d' % WS_PORT)
self.websocket_server = make_server(
'', WS_PORT,
server_class=WSGIServer,
handler_class=WebSocketWSGIRequestHandler,
app=WebSocketWSGIApplication(handler_cls=StreamingWebSocket))
self.websocket_server.initialize_websockets_manager()
self.websocket_thread = Thread(target=self.websocket_server.serve_forever)
print('Initializing HTTP server on port %d' % HTTP_PORT)
self.http_server = StreamingHttpServer()
self.http_thread = Thread(target=self.http_server.serve_forever)
print('Initializing broadcast thread')
output = BroadcastOutput(self.camera)
self.broadcast_thread = BroadcastThread(output.converter, self.websocket_server)
print('Starting recording')
self.camera.start_recording(output, 'yuv')
print('Starting websockets thread')
self.websocket_thread.start()
print('Starting HTTP server thread')
self.http_thread.start()
print('Starting broadcast thread')
self.broadcast_thread.start()
print("Video Stream available...")
while True:
self.camera.wait_recording(1)
def cleanup(self):
# Stop video server - close browser tab before calling cleanup
print('Stopping recording')
self.camera.stop_recording()
print('Waiting for broadcast thread to finish')
self.broadcast_thread.join()
print('Shutting down HTTP server')
self.http_server.shutdown()
print('Shutting down websockets server')
self.websocket_server.shutdown()
print('Waiting for HTTP server thread to finish')
self.http_thread.join()
print('Waiting for websockets thread to finish')
self.websocket_thread.join()
def main():
server = Server()
print(server)
def endProcess(signum = None, frame = None):
# Called on process termination.
if signum is not None:
SIGNAL_NAMES_DICT = dict((getattr(signal, n), n) for n in dir(signal) if n.startswith('SIG') and '_' not in n )
print("signal {} received by process with PID {}".format(SIGNAL_NAMES_DICT[signum], os.getpid()))
print("\n-- Terminating program --")
print("Cleaning up Server...")
server.cleanup()
print("Done.")
exit(0)
# Assign handler for process exit
signal.signal(signal.SIGTERM, endProcess)
signal.signal(signal.SIGINT, endProcess)
signal.signal(signal.SIGHUP, endProcess)
signal.signal(signal.SIGQUIT, endProcess)
server.start()
if __name__ == '__main__':
main()