-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.py
More file actions
181 lines (144 loc) · 4.21 KB
/
Copy pathmain.py
File metadata and controls
181 lines (144 loc) · 4.21 KB
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
#! /usr/bin/env python3
#
# Control program for V4L2NDI
# Loop:
# - find usb video devices
# - run v4l2ndi as a subprocess to translate video to NDU
# - run a separate browser thread for configuration and control
#
# this must run as root, in order to be able to use 'nice' and 'shutdown'
#
#
from wsgiref.simple_server import make_server
import multipart
import io
import os
import time
import re
import threading
import subprocess
import data_files
if os.getuid() == 0:
listensocket = 80
else:
listensocket = 8000
v4l2ndi = "/etc/v4l2ndi/run_v4l2ndi"
def reboot (reboot_flag=True):
""" try to reboot the system """
if reboot_flag:
flag = "-r"
else:
flag = "-h"
args = [
"/usr/sbin/shutdown",
flag,
"now"
]
try:
subprocess.run(args)
except FileNotFoundError:
pass
def shutdown ():
""" try to shut down the system """
reboot(False)
def schedule_task(action, delay):
""" thread task to perform scheduled work """
time.sleep(delay)
action()
def schedule(action, delay=2):
""" schedule an action to occur after a delay"""
threading.Thread(target=(lambda: schedule_task(action, delay))).start()
def webpage(msg=None):
""" return the HTML body of a webpage. "
msg" is an optional text to insert
"""
try:
with open(data_files.html_index) as f, io.BytesIO(b'') as of:
for line in f:
m = re.search("!MSG!", line)
if m is not None:
if msg is not None:
of.write(bytes('<p>', "utf-8"))
of.write(bytes(msg, "utf-8"))
of.write(bytes('<br><p>', "utf-8"))
else:
of.write(bytes(line, "utf-8"))
return of.getvalue()
except FileNotFoundError:
return None
def handle_form(form):
""" handle a form """
if form.get("Restart"):
v4l2ndi_kill()
body = webpage("Restarting V4L2NDI")
elif form.get("Reboot"):
schedule(reboot)
body = webpage("Rebooting")
elif form.get("Shutdown"):
schedule(shutdown)
body = webpage("Shutting down")
else:
body = webpage("Unexpected action")
return body
def my_web_app(environ, start_response):
status = '200 OK'
if environ['REQUEST_METHOD'] == 'GET':
body = webpage()
elif multipart.is_form_request(environ):
forms, files = multipart.parse_form_data(environ)
body = handle_form(forms)
else:
body = None
if body is None:
status = "404 not found"
body = bytes("<html><body><p>internal error</p></body></html>", 'utf-8')
headers = [('Content-Type', 'text/html'),
('Content-Length', str(len(body)))]
start_response(status, headers)
return [body]
#
#
v4l2ndi_terminate_process = False
def v4l2ndi_kill():
global v4l2ndi_terminate_process
v4l2ndi_terminate_process = True
def run_v4l2ndi():
while True:
args = [
v4l2ndi
]
popen = subprocess.Popen(args)
return popen
#
# Periodically clean up dead children
#
v4l2ndi_thread_exit = False
def v4l2ndi_thread():
global v4l2ndi_terminate_process, v4l2ndi_thread_exit
while True:
v4l2ndi_terminate_process = False
popen = run_v4l2ndi()
if popen is None:
time.sleep(10)
else:
while popen.returncode is None:
try:
popen.wait(2)
except (subprocess.TimeoutExpired, KeyboardInterrupt):
pass
finally:
if v4l2ndi_terminate_process:
popen.terminate()
v4l2ndi_terminate_process = False
if v4l2ndi_thread_exit:
return
pass
if __name__ == '__main__' :
threading.Thread(target=v4l2ndi_thread).start()
try:
print(f"webserver listening on port {listensocket}")
with make_server('', listensocket, my_web_app) as httpd:
httpd.serve_forever()
except KeyboardInterrupt:
v4l2ndi_kill()
v4l2ndi_thread_exit = True