-
Notifications
You must be signed in to change notification settings - Fork 1
/
videostreamingapp.py
99 lines (86 loc) · 2.68 KB
/
videostreamingapp.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
from threading import Thread, Condition
from flask import Response, Flask, render_template_string
import topics
# import msgs
class EndpointAction(object):
def __init__(self, action, mimetype=None, headers=None):
self.action = action
self.mimetype = mimetype
self.headers = headers
def __call__(self, *args):
# Perform the action
answer = self.action()
# Create the answer (bundle it in a correctly formatted HTTP answer)
self.response = Response(
answer,
status=200,
mimetype=self.mimetype,
headers=self.headers
)
# Send it
return self.response
class VideoStreamingApp(object):
app = None
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.stopped = True
self.latest_image_jpeg = None
self.image_condition = Condition()
self.app = Flask(__name__) # initialize a flask object
self.app.add_url_rule(
'/', '/', EndpointAction(self.index, headers={})
)
self.app.add_url_rule(
'/video_feed',
'/video_feed',
EndpointAction(
self.generate_images,
mimetype='multipart/x-mixed-replace; boundary=frame'
)
)
def receive_msg(self, msg, topic):
if topic == topics.TOPIC_IMAGE_JPEG:
self.latest_image_jpeg = msg.image
with self.image_condition:
self.image_condition.notify_all()
return
def start(self, **kwargs):
self.output_stream = Thread(
target=self.app.run,
args=(self.ip, self.port),
kwargs=kwargs
)
self.output_stream.daemon = True
self.stopped = False
self.output_stream.start()
def index(self):
''' return the rendered template '''
page = '''\
<html>
<head>
<title>UAV Monitoring</title>
</head>
<body>
<center>
<h1>UAV Monitoring</h1>
</center>
<center>
<img src="{{ url_for('/video_feed') }}" >
</center>
</body>
</html>
'''
return render_template_string(page)
# return render_template('index.html')
def generate_images(self):
"""Image streaming generator function."""
while not self.stopped:
with self.image_condition:
self.image_condition.wait()
image = self.latest_image_jpeg
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + image + b'\r\n')
def stop(self):
self.stopped = True
self.output_stream.join(5)