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

  • 2
    A good question, but you might get a better answer on stackoverflow.com – Mawg says reinstate Monica Dec 18 '19 at 8:27
  • Have you considered threading? – Mawg says reinstate Monica Dec 20 '19 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 😊 – Archit Kithania Dec 21 '19 at 13:55
  • Congrats! Now, could you please post (and accept) an answer, which will help others in future. Thanks – Mawg says reinstate Monica Dec 21 '19 at 13:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.