1

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

3
  • 2
    A good question, but you might get a better answer on stackoverflow.com
    – Mawg
    Commented Dec 18, 2019 at 8:27
  • Have you considered threading?
    – Mawg
    Commented Dec 20, 2019 at 8:11
  • I have but threading introduced too much of an overhead. I have gotten this socket approach to finally work so no need. Thanks for you help though 😊 Commented Dec 21, 2019 at 13:55

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.