websocketpython-asyncioesp32micropython

Asyncio stop waiting for socket


I'm trying to write a code in micropython for ESP32.

ESP32 need to write in LCD Display by example every 10 seconds, and too response in one web server. But when go to web server code section, it stop, until web client consult (socket). I'm trying to use asyncio. I write a code to simulate my situation, but i dosen't work. I'dont know why. Can you help me? sorry about my english. Regards.

import asyncio
async def eternity():
    # Sleep until enter press
    x=input("Press enter..")

async def main():
    while True:
        # Wait for at most 1 second
        try:
            await asyncio.wait_for(eternity(), timeout=1.0)
        except asyncio.TimeoutError:
            print('timeout!')
        #await asyncio.sleep(2)

asyncio.run(main())

I wait an output like:

timeout!

timeout!

timeout!

timeout!

Press enter

and evetualy, if I press entre key

The code is adapted from: https://docs.python.org/es/3/library/asyncio-task.html#coroutines


Solution

  • async def eternity():
        # Sleep until enter press
        x=input("Press enter..")
    

    The function above waits for a keypress and it blocks while waiting. It is not an asynchronous code. Yes, there is an async def, but that does not make it doing async I/O. And Synchronous I/O cannot time-out and be interrupted by the asyncio.

    Please make sure you understand what asyncio can do. It can run several tasks concurrently, but not parallel. Only one at a time and the only place a task switch can occur is at an await. If the active task cannot immediately continue, asyncio will run another task instead.