micropython中具有多种方法的asyncio

asyncio with multiple methods in micropython

当我 运行 下面的代码时,它 运行s 并打印 ("Listening, connect your APP to http://192.168.4.1:8080/") 并作为 Web 服务器等待请求。在 Web 服务器模式下,我希望 LED 闪烁,这就是我应用 asyncio 的原因。

但是,除非它收到任何请求(这会激活网络服务器中的 While True: 循环),否则 LED 不会响应。我尝试了很多方法,但我找不到在网络服务器模式下切换 LED 的方法。您可以在下面的代码中看到关于 await asyncio.sleep(20) 的评论:

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()

您的 webServer 异步函数并不是真正的异步,因为它使用 阻塞 IO。至少您需要将套接字设置为非阻塞模式并使用套接字操作provided by asyncio, or even better you should use asyncio.start_server 来实现异步网络服务器。

请参阅 asyncio 文档或例如 例如。