Skip to content

Commit fc6b32f

Browse files
authored
Add files via upload
upload local files
1 parent 9669381 commit fc6b32f

File tree

5 files changed

+826
-0
lines changed

5 files changed

+826
-0
lines changed

firmware/esp32-cam-micropython.bin

1.15 MB
Binary file not shown.

src/googleDriveTest.py

Lines changed: 129 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,129 @@
1+
#!/usr/bin/env micropython
2+
# -*- coding: utf-8 -*-
3+
4+
import network
5+
from machine import Pin, Timer, I2C, ADC
6+
import camera
7+
import machine
8+
import time
9+
import uasyncio as asyncio
10+
import ubinascii
11+
import gc
12+
import usocket
13+
import json
14+
import urequests
15+
16+
__author__ = "Marciel Barros Pereira"
17+
__credits__ = ["Marciel Barros Pereira"]
18+
__maintainer__ = "Marciel Barros Pereira"
19+
__email__ = "[email protected]"
20+
21+
22+
23+
24+
sta_if = network.WLAN(network.STA_IF)
25+
sta_if.active(True)
26+
try:
27+
sta_if.disconnect()
28+
except:
29+
pass
30+
redes = sta_if.scan()
31+
32+
knownSsid = [b'put',b'your',b'known',b'essid-here']
33+
knownPasswd = [b'put',b'known-essid',b'passwords',b'here']
34+
35+
ssidmode = False
36+
for i in range (0,len(knownSsid)):
37+
for j in range (0,len(redes)):
38+
print("Compare {} with {}".format(knownSsid[i],redes[j][0]))
39+
if (knownSsid[i]==redes[j][0]):
40+
print("Connecting to {}".format(knownSsid[i]))
41+
sta_if.connect(knownSsid[i],knownPasswd[i])
42+
while sta_if.isconnected() == False:
43+
pass
44+
print('Connection successful')
45+
ssid = knownSsid[i]
46+
ssidmode = True
47+
print(sta_if.ifconfig())
48+
break
49+
# check framesize modes in https://github.com/shariltumin/esp32-cam-micropython
50+
camera.init()
51+
camera.framesize(5)
52+
buf = camera.capture()
53+
camera.deinit()
54+
55+
# there is no need to save right now, but, if you want to save file, use followigng code
56+
# newFile = open("ESP32-CAM.jpg", "wb")
57+
# newFile.write(buf)
58+
# newFile.close()
59+
60+
# Create base64 string from image bytearray
61+
bufBase64 = ubinascii.b2a_base64(buf)
62+
63+
# gather some free memory
64+
gc.collect()
65+
66+
myScriptID = 'putYourScriptIdHere'
67+
url = 'https://script.google.com/macros/s/'+myScriptID+'/exec'
68+
myScript = '/macros/s/'+myScriptID+'/exec'
69+
70+
myFilename = "filename=ESP32-CAM.jpg&mimetype=image/jpeg&data="
71+
#myFilename = "imgBase64="
72+
myDomain = "script.google.com"
73+
74+
# below lines were adapted from urequests lib
75+
76+
a = bufBase64.decode()
77+
data = myFilename + a
78+
method = "POST"
79+
try:
80+
proto, dummy, host, path = url.split("/", 3)
81+
except ValueError:
82+
proto, dummy, host = url.split("/", 2)
83+
path = ""
84+
if proto == "http:":
85+
port = 80
86+
elif proto == "https:":
87+
import ussl
88+
port = 443
89+
else:
90+
raise ValueError("Unsupported protocol: " + proto)
91+
92+
if ":" in host:
93+
host, port = host.split(":", 1)
94+
port = int(port)
95+
96+
ai = usocket.getaddrinfo(host, port, 0, usocket.SOCK_STREAM)
97+
ai = ai[0]
98+
99+
s = usocket.socket(ai[0], ai[1], ai[2])
100+
101+
s.connect(ai[-1])
102+
if proto == "https:":
103+
s = ussl.wrap_socket(s, server_hostname=host)
104+
s.write(b"%s /%s HTTP/1.0\r\n" % (method, path))
105+
106+
s.write(b"Host: %s\r\n" % host)
107+
# Iterate over keys to avoid tuple alloc
108+
s.write(b"Content-Length: %d\r\n" % len(data))
109+
s.write(b"Content-Type: application/x-www-form-urlencoded\r\n")
110+
s.write(b"\r\n")
111+
112+
s.write(data)
113+
114+
l = s.readline()
115+
116+
l = l.split(None, 2)
117+
status = int(l[1])
118+
reason = ""
119+
if len(l) > 2:
120+
reason = l[2].rstrip()
121+
while True:
122+
l = s.readline()
123+
if not l or l == b"\r\n":
124+
break
125+
if l.startswith(b"Transfer-Encoding:"):
126+
if b"chunked" in l:
127+
raise ValueError("Unsupported " + l)
128+
elif l.startswith(b"Location:") and not 200 <= status <= 299:
129+
raise NotImplementedError("Redirects not yet supported")

src/uasyncio/__init__.py

Lines changed: 258 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,258 @@
1+
import uerrno
2+
import uselect as select
3+
import usocket as _socket
4+
from uasyncio.core import *
5+
6+
7+
DEBUG = 0
8+
log = None
9+
10+
def set_debug(val):
11+
global DEBUG, log
12+
DEBUG = val
13+
if val:
14+
import logging
15+
log = logging.getLogger("uasyncio")
16+
17+
18+
class PollEventLoop(EventLoop):
19+
20+
def __init__(self, runq_len=16, waitq_len=16):
21+
EventLoop.__init__(self, runq_len, waitq_len)
22+
self.poller = select.poll()
23+
self.objmap = {}
24+
25+
def add_reader(self, sock, cb, *args):
26+
if DEBUG and __debug__:
27+
log.debug("add_reader%s", (sock, cb, args))
28+
if args:
29+
self.poller.register(sock, select.POLLIN)
30+
self.objmap[id(sock)] = (cb, args)
31+
else:
32+
self.poller.register(sock, select.POLLIN)
33+
self.objmap[id(sock)] = cb
34+
35+
def remove_reader(self, sock):
36+
if DEBUG and __debug__:
37+
log.debug("remove_reader(%s)", sock)
38+
self.poller.unregister(sock)
39+
del self.objmap[id(sock)]
40+
41+
def add_writer(self, sock, cb, *args):
42+
if DEBUG and __debug__:
43+
log.debug("add_writer%s", (sock, cb, args))
44+
if args:
45+
self.poller.register(sock, select.POLLOUT)
46+
self.objmap[id(sock)] = (cb, args)
47+
else:
48+
self.poller.register(sock, select.POLLOUT)
49+
self.objmap[id(sock)] = cb
50+
51+
def remove_writer(self, sock):
52+
if DEBUG and __debug__:
53+
log.debug("remove_writer(%s)", sock)
54+
try:
55+
self.poller.unregister(sock)
56+
self.objmap.pop(id(sock), None)
57+
except OSError as e:
58+
# StreamWriter.awrite() first tries to write to a socket,
59+
# and if that succeeds, yield IOWrite may never be called
60+
# for that socket, and it will never be added to poller. So,
61+
# ignore such error.
62+
if e.args[0] != uerrno.ENOENT:
63+
raise
64+
65+
def wait(self, delay):
66+
if DEBUG and __debug__:
67+
log.debug("poll.wait(%d)", delay)
68+
# We need one-shot behavior (second arg of 1 to .poll())
69+
res = self.poller.ipoll(delay, 1)
70+
#log.debug("poll result: %s", res)
71+
# Remove "if res" workaround after
72+
# https://github.com/micropython/micropython/issues/2716 fixed.
73+
if res:
74+
for sock, ev in res:
75+
cb = self.objmap[id(sock)]
76+
if ev & (select.POLLHUP | select.POLLERR):
77+
# These events are returned even if not requested, and
78+
# are sticky, i.e. will be returned again and again.
79+
# If the caller doesn't do proper error handling and
80+
# unregister this sock, we'll busy-loop on it, so we
81+
# as well can unregister it now "just in case".
82+
self.remove_reader(sock)
83+
if DEBUG and __debug__:
84+
log.debug("Calling IO callback: %r", cb)
85+
if isinstance(cb, tuple):
86+
cb[0](*cb[1])
87+
else:
88+
cb.pend_throw(None)
89+
self.call_soon(cb)
90+
91+
92+
class StreamReader:
93+
94+
def __init__(self, polls, ios=None):
95+
if ios is None:
96+
ios = polls
97+
self.polls = polls
98+
self.ios = ios
99+
100+
def read(self, n=-1):
101+
while True:
102+
yield IORead(self.polls)
103+
res = self.ios.read(n)
104+
if res is not None:
105+
break
106+
# This should not happen for real sockets, but can easily
107+
# happen for stream wrappers (ssl, websockets, etc.)
108+
#log.warn("Empty read")
109+
if not res:
110+
yield IOReadDone(self.polls)
111+
return res
112+
113+
def readexactly(self, n):
114+
buf = b""
115+
while n:
116+
yield IORead(self.polls)
117+
res = self.ios.read(n)
118+
assert res is not None
119+
if not res:
120+
yield IOReadDone(self.polls)
121+
break
122+
buf += res
123+
n -= len(res)
124+
return buf
125+
126+
def readline(self):
127+
if DEBUG and __debug__:
128+
log.debug("StreamReader.readline()")
129+
buf = b""
130+
while True:
131+
yield IORead(self.polls)
132+
res = self.ios.readline()
133+
assert res is not None
134+
if not res:
135+
yield IOReadDone(self.polls)
136+
break
137+
buf += res
138+
if buf[-1] == 0x0a:
139+
break
140+
if DEBUG and __debug__:
141+
log.debug("StreamReader.readline(): %s", buf)
142+
return buf
143+
144+
def aclose(self):
145+
yield IOReadDone(self.polls)
146+
self.ios.close()
147+
148+
def __repr__(self):
149+
return "<StreamReader %r %r>" % (self.polls, self.ios)
150+
151+
152+
class StreamWriter:
153+
154+
def __init__(self, s, extra):
155+
self.s = s
156+
self.extra = extra
157+
158+
def awrite(self, buf, off=0, sz=-1):
159+
# This method is called awrite (async write) to not proliferate
160+
# incompatibility with original asyncio. Unlike original asyncio
161+
# whose .write() method is both not a coroutine and guaranteed
162+
# to return immediately (which means it has to buffer all the
163+
# data), this method is a coroutine.
164+
if sz == -1:
165+
sz = len(buf) - off
166+
if DEBUG and __debug__:
167+
log.debug("StreamWriter.awrite(): spooling %d bytes", sz)
168+
while True:
169+
res = self.s.write(buf, off, sz)
170+
# If we spooled everything, return immediately
171+
if res == sz:
172+
if DEBUG and __debug__:
173+
log.debug("StreamWriter.awrite(): completed spooling %d bytes", res)
174+
return
175+
if res is None:
176+
res = 0
177+
if DEBUG and __debug__:
178+
log.debug("StreamWriter.awrite(): spooled partial %d bytes", res)
179+
assert res < sz
180+
off += res
181+
sz -= res
182+
yield IOWrite(self.s)
183+
#assert s2.fileno() == self.s.fileno()
184+
if DEBUG and __debug__:
185+
log.debug("StreamWriter.awrite(): can write more")
186+
187+
# Write piecewise content from iterable (usually, a generator)
188+
def awriteiter(self, iterable):
189+
for buf in iterable:
190+
yield from self.awrite(buf)
191+
192+
def aclose(self):
193+
yield IOWriteDone(self.s)
194+
self.s.close()
195+
196+
def get_extra_info(self, name, default=None):
197+
return self.extra.get(name, default)
198+
199+
def __repr__(self):
200+
return "<StreamWriter %r>" % self.s
201+
202+
203+
def open_connection(host, port, ssl=False):
204+
if DEBUG and __debug__:
205+
log.debug("open_connection(%s, %s)", host, port)
206+
ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
207+
ai = ai[0]
208+
s = _socket.socket(ai[0], ai[1], ai[2])
209+
s.setblocking(False)
210+
try:
211+
s.connect(ai[-1])
212+
except OSError as e:
213+
if e.args[0] != uerrno.EINPROGRESS:
214+
raise
215+
if DEBUG and __debug__:
216+
log.debug("open_connection: After connect")
217+
yield IOWrite(s)
218+
# if __debug__:
219+
# assert s2.fileno() == s.fileno()
220+
if DEBUG and __debug__:
221+
log.debug("open_connection: After iowait: %s", s)
222+
if ssl:
223+
print("Warning: uasyncio SSL support is alpha")
224+
import ussl
225+
s.setblocking(True)
226+
s2 = ussl.wrap_socket(s)
227+
s.setblocking(False)
228+
return StreamReader(s, s2), StreamWriter(s2, {})
229+
return StreamReader(s), StreamWriter(s, {})
230+
231+
232+
def start_server(client_coro, host, port, backlog=10):
233+
if DEBUG and __debug__:
234+
log.debug("start_server(%s, %s)", host, port)
235+
ai = _socket.getaddrinfo(host, port, 0, _socket.SOCK_STREAM)
236+
ai = ai[0]
237+
s = _socket.socket(ai[0], ai[1], ai[2])
238+
s.setblocking(False)
239+
240+
s.setsockopt(_socket.SOL_SOCKET, _socket.SO_REUSEADDR, 1)
241+
s.bind(ai[-1])
242+
s.listen(backlog)
243+
while True:
244+
if DEBUG and __debug__:
245+
log.debug("start_server: Before accept")
246+
yield IORead(s)
247+
if DEBUG and __debug__:
248+
log.debug("start_server: After iowait")
249+
s2, client_addr = s.accept()
250+
s2.setblocking(False)
251+
if DEBUG and __debug__:
252+
log.debug("start_server: After accept: %s", s2)
253+
extra = {"peername": client_addr}
254+
yield client_coro(StreamReader(s2), StreamWriter(s2, extra))
255+
256+
257+
import uasyncio.core
258+
uasyncio.core._event_loop_class = PollEventLoop

0 commit comments

Comments
 (0)