-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathasync_tasks_webcam_sta.py
309 lines (274 loc) · 6.81 KB
/
async_tasks_webcam_sta.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
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import usocket as soc
import uasyncio as sy
import camera
import time
import esp
from machine import Pin
import gc
from Wifi.Sta import Sta
#esp.osdebug(False)
esp.osdebug(True)
def foo(p):
print('FOO here', p[0]+p[1])
async def bar(p):
print('BAR here', p[1]*p[2])
c = p[0]
if c > 0:
yield
bar([c-1, 3, 2+c]) # call me again
hdr = {
# start page for streaming
# URL: /apikey/webcam
'live': """HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
<html>
<head>
<title>Video Streaming Demonstration</title>
</head>
<body>
<center>
<h1>Video Streaming Demonstration</h1>
<img src="/apikey/live" width=720 height=540 />
</center>
</body>
</html>
""",
# live stream -
# URL: /apikey/live
'stream': """HTTP/1.1 200 OK
Content-Type: multipart/x-mixed-replace; boundary=frame
Connection: keep-alive
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: Thu, Jan 01 1970 00:00:00 GMT
Pragma: no-cache
""",
# live stream -
# URL:
'frame': """--frame
Content-Type: image/jpeg
""",
# still picture -
# URL: /apikey/snap
'snap': """HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: """,
# no content error
# URL: all the rest
'none': """HTTP/1.1 204 No Content
Content-Type: text/plain; charset=utf-8
Nothing here!
""",
# bad request error
# URL: /favicon.ico
'favicon': """HTTP/1.1 404
""",
# bad request error
# URL: all the rest
'err': """HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
Hello? Can not compile
""",
# test
# URL: all the rest
'test': """HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Hello there!
"""
}
def clean_up(cs):
cs.close() # flash buffer and close socket
del cs
gc.collect()
def frame_gen():
#buf = b' '
while True:
buf = camera.capture()
yield buf
del buf
gc.collect()
async def send_frame(pp):
cs, h = pp
while True:
ee = ''
try:
cs.send(b'%s' % h)
#cs.send(camera.capture())
cs.send(next(pic))
cs.send(b'\r\n') # send and flush the send buffer
except Exception as e:
ee = str(e)
if ee == '':
await sy.sleep_ms(5) # try as fast as we can
else:
break
clean_up(cs)
return
def servers():
socks = []
# port 80 server - streaming server
s = soc.socket(soc.AF_INET, soc.SOCK_STREAM)
s.setsockopt(soc.SOL_SOCKET, soc.SO_REUSEADDR, 1)
a = ('0.0.0.0', 80)
s.bind(a)
s.listen(3) # at most 3 clients
socks.append(s)
# port 81 server - still picture server
s = soc.socket(soc.AF_INET, soc.SOCK_STREAM)
s.setsockopt(soc.SOL_SOCKET, soc.SO_REUSEADDR, 1)
a = ('0.0.0.0', 81)
s.bind(a)
s.listen(3)
socks.append(s)
# port 82 server - cmd server
s = soc.socket(soc.AF_INET, soc.SOCK_STREAM)
s.setsockopt(soc.SOL_SOCKET, soc.SO_REUSEADDR, 1)
a = ('0.0.0.0', 82)
s.bind(a)
s.listen(3)
socks.append(s)
return socks
async def port1(cs, rq):
rqp = rq[1].split('/')
if rqp[1] == 'apikey': # Must have /apikey/<REQ>
if rqp[2] == 'webcam':
cs.send(b'%s' % hdr['live'])
clean_up(cs)
elif rqp[2] == 'live': # start streaming
cs.send(b'%s' % hdr['stream'])
# schedule frame sending
await send_frame([cs, hdr['frame']])
else: #
cs.send(b'%s' % hdr['none'])
clean_up(cs)
else:
cs.send(b'%s' % hdr['err'])
clean_up(cs)
async def port2(cs, rq):
rqp = rq[1].split('/')
if rqp[1] == 'apikey': # Must have /apikey/<REQ>
if rqp[2] == 'snap':
try:
#img=camera.capture()
img=next(pic)
cs.send(b'%s %d\r\n\r\n' % (hdr['snap'], len(img)))
cs.send(img)
cs.send(b'\r\n')
except:
pass
elif rqp[2] == 'blitz':
try:
flash_light.on()
#img=camera.capture()
img=next(pic)
flash_light.off()
cs.send(b'%s %d\r\n\r\n' % (hdr['snap'], len(img)))
cs.send(img)
cs.send(b'\r\n')
except:
pass
else:
cs.send(b'%s' % hdr['none'])
else:
cs.send(b'%s' % hdr['err'])
clean_up(cs)
async def port3(cs, rq):
rqp = rq[1].split('/')
if rqp[1] == 'apikey': # Must have /apikey/<REQ>
if rqp[2] == 'flash': # /apikey/flash/<what>
if rqp[3] == 'on':
flash_light.on()
else:
flash_light.off()
cs.send(b'%s' % hdr['test'])
else:
cs.send(b'%s' % hdr['test'])
else:
loop.create_task(foo([7, 5]))
cs.send(b'%s' % hdr['test'])
clean_up(cs)
async def srv(p):
sa = socks[p] # scheduled server
while True:
ok = True
ee = ''
yield
try:
sa.settimeout(0.05) # in sec NB! default browser timeout (5-15 min)
cs, ca = sa.accept()
cs.settimeout(0.5) # in sec
except Exception as e:
ee = str(e)
if ee != '':
# print('Socket %d accept - %s' % (p, ee.split()[-1]))
#ee = ''
pass
ok = False
yield
if ok: # No soc.accept timeout
ee = ''
try:
# client accepted
r = cs.recv(1024)
# REQ: b'' # may be due to very short timeout
except Exception as e:
ee = str(e)
if ee != '':
print(ee)
ok = False
else:
ms = r.decode('utf-8')
if ms.find('favicon.ico') < 0:
rq = ms.split(' ')
print(rq[0], rq[1], ca)
else:
cs.send(b'%s' % hdr['favicon']) # handle favicon request early
clean_up(cs)
ok = False
yield
if ok: # No soc.recv timeout or favicon request
await ports[p](cs, rq)
wc = 0
while True:
cr = camera.init()
print("Camera ready?: ", cr)
if cr:
break
time.sleep(2)
wc += 1
if wc >= 5:
break
if not cr:
print("Camera not ready. Can't continue!")
else:
w = Sta()
w.connect()
w.wait()
wc = 0
while not w.wlan.isconnected():
print("WIFI not ready. Wait...")
time.sleep(2)
wc += 1
if wc >= 5:
break
if wc >= 5:
print("WIFI not ready. Can't continue!")
else:
pic = frame_gen()
flash_light = Pin(04,Pin.OUT)
socks = servers()
ports = [port1, port2, port3] # 80, 81, 82
loop = sy.get_event_loop()
# schedule each srv twice
for i in range(len(socks)):
if i == 0:
loop.create_task(srv(i)) # schedule 2 servers for port 80
loop.create_task(srv(i)) # streaming hold socket until client
# terminate, we service at most 2 clients
else:
loop.create_task(srv(i)) # only one for 81 and 82
#
# schedule other processes here
#
# go for it!
print("Up Up and Away!")
loop.run_forever()