-
-
Notifications
You must be signed in to change notification settings - Fork 34
/
Copy path_P522_CameraGateway.py
264 lines (247 loc) · 8.14 KB
/
_P522_CameraGateway.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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#!/usr/bin/env python3
#############################################################################
################## RTSP to JPEG proxy plugin for RPIEasy ####################
#############################################################################
#
# Plugin which transforms a realtime stream or any OpenCV datasource into JPEG image
# for example Domoticz camera integration
#
# Copyright (C) 2020 by Alexander Nagy - https://bitekmindenhol.blog.hu/
#
import plugin
import webserver
import rpieGlobals
import rpieTime
import misc
import time
import webserver
import Settings
from PIL import Image, ImageDraw
from io import BytesIO
from threading import Thread
import cv2
import os
class Plugin(plugin.PluginProto):
PLUGIN_ID = 522
PLUGIN_NAME = "Image - OpenCV RTSP stream To JPEG"
PLUGIN_VALUENAME1 = "jpeg"
def __init__(self,taskindex): # general init
plugin.PluginProto.__init__(self,taskindex)
self.dtype = rpieGlobals.DEVICE_TYPE_DUMMY
self.vtype = rpieGlobals.SENSOR_TYPE_NONE
self.readinprogress = 0
self.valuecount = 0
self.senddataoption = False
self.timeroption = False
self.timeroptional = True
self.formulaoption = False
self._nextdataservetime = 0
self.lastread = 0
self.videostream = None
self.lastinit = 0
def plugin_init(self,enableplugin=None):
plugin.PluginProto.plugin_init(self,enableplugin)
self.uservar[0] = 0
if enableplugin is None:
try:
if self.videostream:
del self.videostream
except:
pass
self.initialized = False
self.readinprogress = 0
if self.enabled:
# rtsp_stream_link = 'rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov'
if self.taskdevicepluginconfig[4]:
os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = "rtsp_transport;udp"
rtsp_stream_link = str(self.taskdevicepluginconfig[0])
try:
self.videostream = VideoGrab(rtsp_stream_link)
self.initialized = True
except Exception as e:
pass
if self.videostream is None:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Videostream can not be initialized! ")
return False
else:
if time.time()-self.lastinit>10:
self.capture_start()
self.lastinit = time.time()
else:
try:
self.capture_stop()
del self.videostream
except:
pass
def webform_load(self): # create html page for settings
webserver.addFormTextBox("RTSP stream","plugin_522_url",str(self.taskdevicepluginconfig[0]),255)
webserver.addFormNote("Specify the full URL to access stream, with password if needed")
webserver.addFormCheckBox("Enable resize","plugin_522_resize",self.taskdevicepluginconfig[1])
webserver.addFormNumericBox("Width to resize","plugin_522_w",self.taskdevicepluginconfig[2],0,4096)
webserver.addFormNumericBox("Height to resize","plugin_522_h",self.taskdevicepluginconfig[3],0,2160)
webserver.addFormNote("Resize is a bit resource hungry, use only if really needed")
webserver.addFormCheckBox("Force FFMPEG UDP","plugin_522_udp",self.taskdevicepluginconfig[4])
webserver.addFormNote("Certain cheap cameras only knows UDP, and OpenCV >3.0 defaults to TCP. OpenCV >4.0 accepts override.")
webserver.addFormNote("In case the installed opencv is too old, upgrade manually: 'sudo apt remove python3-opencv && sudo pip3 install opencv-python'")
try:
if self.initialized and self.enabled:
try:
pname = self.gettaskname()
except:
pname = ""
if pname=="":
pname = "[NAME]"
url = "image?name="+str(pname)
webserver.addHtml("<tr><td>Output image url:</td>")
if pname == "[NAME]":
webserver.addHtml("<td>http://ipaddress:port/image?name="+pname)
else:
webserver.addHtml("<td><a href='"+url+"'>/"+url+"</a></td></tr>")
except:
pass
return True
def webform_save(self,params): # process settings post reply
self.capture_stop()
self.taskdevicepluginconfig[0] = webserver.arg("plugin_522_url",params)
self.taskdevicepluginconfig[1] = (webserver.arg("plugin_522_resize",params)=="on")
self.taskdevicepluginconfig[2] = int(webserver.arg("plugin_522_w",params))
self.taskdevicepluginconfig[3] = int(webserver.arg("plugin_522_h",params))
self.taskdevicepluginconfig[4] = (webserver.arg("plugin_522_udp",params)=="on")
self.capture_start(self.taskdevicepluginconfig[0])
return True
def capture_start(self,src=None):
try:
# if self.videostream.initialized==False:
self.videostream.start(src)
except Exception as e:
misc.addLog(rpieGlobals.LOG_LEVEL_ERROR,"Videostream can not be initialized! "+str(e))
def capture_stop(self):
try:
self.videostream.stop()
except:
pass
def plugin_exit(self):
plugin.PluginProto.plugin_exit(self)
try:
if self.videostream is not None:
self.videostream.__exit__()
self.videostream = None
except:
pass
class VideoGrab(object):
def __init__(self, src=0):
# Create a VideoCapture object
self.initialized = False
self.status = False
self.src = src
self.delaytime = 1/20
def start(self,src=None):
if src is not None:
self.src = src
try:
self.capture = cv2.VideoCapture(self.src)
self.initialized = True
except Exception as e:
self.initialized = False
self.capture = None
# print(e)
if self.initialized:
starttime = time.time()
try:
if self.capture.isOpened():
waittostart = True
while waittostart: # wait until accessible
(self.status, frame) = self.capture.read()
if (self.status and frame is not None) or (time.time()-startime>10):
waittostart = False
time.sleep(0.1)
except:
pass
# Start the thread to read frames from the video stream
thread = Thread(target=self.update, args=())
thread.daemon = True
thread.start()
def __exit__(self):
self.stop()
try:
self.capture.release()
except:
pass
self.capture = None
def stop(self):
if self.initialized:
self.initialized = False
time.sleep(0.5)
def update(self):
# Read the next frame from the stream in a different thread
while self.initialized:
try:
if self.capture.isOpened():
self.status = self.capture.grab()
else:
time.sleep(1)
time.sleep(self.delaytime)
except Exception as e:
pass
try:
self.capture.release()
except:
pass
def get_frame(self):
if self.initialized==False:
self.start()
if self.initialized:
try:
(self.status, frame) = self.capture.retrieve()
except Exception as e:
pass
return frame
else:
return None
@webserver.WebServer.route('/image')
def handle_videostream(self):
tname = ""
try:
if (not webserver.isLoggedIn(self.get,self.cookie)):
return self.redirect('/login')
if self.type == "GET":
responsearr = self.get
else:
responsearr = self.post
if responsearr:
tname = webserver.arg("name",responsearr)
except Exception as e:
print(e)
vidtask = None
for x in range(0,len(Settings.Tasks)):
if (Settings.Tasks[x]) and type(Settings.Tasks[x]) is not bool:
try:
if Settings.Tasks[x].enabled:
if Settings.Tasks[x].pluginid==522 and Settings.Tasks[x].gettaskname()==tname:
vidtask = Settings.Tasks[x]
break
except:
pass
if vidtask is not None:
succ = False
self.set_mime('image/jpeg')
try:
cv2_im = vidtask.videostream.get_frame()
if cv2_im is not None:
cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB)
image = Image.fromarray(cv2_im)
if vidtask.taskdevicepluginconfig[1]:
image = image.resize( (int(vidtask.taskdevicepluginconfig[2]),int(vidtask.taskdevicepluginconfig[3])), Image.LANCZOS)
img_io = BytesIO()
image.save(img_io, 'JPEG')
img_io.seek(0)
succ = True
return img_io.read()
else:
vidtask.capture_start()
return None
except Exception as e:
print(e)
succ = False
if succ==False:
vidtask.capture_start()