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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With