Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asyncio with multiple methods in micropython

When I run the following code, it runs and print ("Listening, connect your APP to http://192.168.4.1:8080/") and waiting request as web server. During the web server mode, I want the LED to blink that's why I have applied asyncio.

However, unless it receives any request (which activates While True: loop in web server), LED does not respond. I have tried many ways but I could not find a way to toggle of LED during web server mode. You can see the comment regarding to await asyncio.sleep(20) in the code below:

import uasyncio as asyncio
from machine import Pin
import time

LED_PIN = 13
led = Pin(LED_PIN, Pin.OUT, value=1)

async def toggle():
    while True:
        await asyncio.sleep_ms(500)
        led.value(not led.value()) # toggling        

async def webServer(ipAddress):
    s = socket.socket()
    ai = socket.getaddrinfo(ipAddress, 8080)
    print("Bind address info:", ai)
    addr = ai[0][-1]
    s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    s.bind(addr)
    s.listen(2)
    print("Listening, connect your APP to http://%s:8080/" % ipAddress)

    counter = 0
    # await asyncio.sleep(20) # !! if i applied await here, LED toggling 20 secs but web server does not accept any request because "while True" below is not activated during 20 secs.
    while True:
        res = s.accept()
        client_sock = res[0]
        client_addr = res[1]
        print("Client address:", client_addr)
        print("Client socket:", client_sock)

        req = client_sock.recv(1024)
        print("Payload: %s" % req.decode())
        client_sock.send(CONTENT % counter)
        client_sock.close()
        counter += 1
        print()

loop = asyncio.get_event_loop()
loop.create_task(toggle())
loop.create_task(webServer('192.168.4.1'))
loop.run_forever()
like image 226
Sunrise17 Avatar asked Dec 05 '25 16:12

Sunrise17


1 Answers

Your webServer async function is not really async because it uses blocking IO. At a minimum you need to set the socket to non-blocking mode and use the socket operations provided by asyncio, or even better you should use asyncio.start_server to implement an asynchronous network server.

See the asyncio documentation or e.g. this answer for examples.

like image 176
user4815162342 Avatar answered Dec 08 '25 08:12

user4815162342



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!