I am using an ESP32 with a MicroPython Firmware and want to make asynchronous HTTP requests such as GET request. I have tried using usocket
but it did kept throwing OSError 128
. I have attached my code for the socket below. I am hoping for a solution that is asynchronous (as I am running multiple coroutines) and therefore is non blocking. The function should take in a URL
and callback
and should invoke the callback with the response of the http request.
# Test url http://jsonplaceholder.typicode.com/todos/1
async def non_blocking_get(url, callback):
BUSY_ERRORS = [uerrno.EINPROGRESS, uerrno.ETIMEDOUT]
# Assume Wifi is connected
if not nic.isconnected():
return
_, _, host, path = url.split('/', 3)
addr = socket.getaddrinfo(host, 80)[0][-1]
s = socket.socket()
s.setblocking(0)
s.connect(addr)
s.send(bytes('GET /%s HTTP/1.0\r\nHost: %s\r\n\r\n' % (path, host), 'utf8'))
msg = None
while True:
try:
msg = s.recv(4096)
except OSError as e:
if e.args[0] not in BUSY_ERRORS:
raise
else:
continue
else:
if len(msg) == 0:
print('Zero size')
msg = None
break
print(msg)
s.close()
callback(msg)
Any help would be highly appreciated. Thank you in advance