-
Notifications
You must be signed in to change notification settings - Fork 0
/
streaming_service.py
87 lines (66 loc) · 2.39 KB
/
streaming_service.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
import logging
import sys
import os
import typing
import threading
from flask import Flask, Response, jsonify, send_from_directory
from flask_cors import CORS
import cv2
from streaming_helpers import CameraInformation
logging.getLogger("werkzeug").disabled = True
os.environ["WERKZEUG_RUN_MAIN"] = "true"
CLI = sys.modules["flask.cli"]
CLI.show_server_banner = lambda *x: None # type: ignore
APP = Flask(__name__, static_folder="hub-client/build")
CORS(APP)
node_services: typing.Dict[str, CameraInformation] = {}
def from_queue(camera_id: str):
service = node_services.get(camera_id)
while service:
image = service.read_frame()
res, im_jpg = cv2.imencode(".jpg", image)
if res:
yield (
b"--frame\r\n"
b"Content-Type: image/jpeg\r\n\r\n" + im_jpg.tostring() + b"\r\n"
)
return None
@APP.route("/nodes", methods=["GET"])
def active_cameras():
cameras = [
dict(nodeId=service.node_id, isOnline=service.is_online)
for service in node_services.values()
]
return jsonify(cameras)
@APP.route("/nodes/<node_id>/video_feed", methods=["GET"])
def video_feed(node_id: str):
return Response(
from_queue(node_id), mimetype="multipart/x-mixed-replace; boundary=frame"
)
# Serve React App
@APP.route("/", defaults={"path": ""})
@APP.route("/<path:path>")
def serve(path):
if path != "" and os.path.exists(APP.static_folder + "/" + path):
return send_from_directory(APP.static_folder, path)
else:
return send_from_directory(APP.static_folder, "index.html")
class StreamingService:
def __init__(self, host="localhost", port=5000):
self.host = host
self.port = port
self._thread = None
def _run(self):
print("starting streaming server on %s:%d" % (self.host, self.port))
print("visit %s:%d to view live camera stream" % (self.host, self.port))
APP.run(host=self.host, port=self.port, debug=False, use_reloader=False)
def start(self):
thread = threading.Thread(target=self._run, daemon=True)
thread.start()
self._thread = thread
def hub_message_handler(self, cam_id, image):
node_service = node_services.get(cam_id)
if not node_service:
node_service = CameraInformation(cam_id)
node_services[cam_id] = node_service
node_service.write_frame(image)