WEB SERVER in AP MODE using asyncio [Solved] #14219
-
Hi,
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
It's much easier, and more robust and comprehensive, to do the web server part like this: https://microdot.readthedocs.io/en/latest/intro.html#a-simple-microdot-web-server |
Beta Was this translation helpful? Give feedback.
-
I have made some changes to your code. I've tested the code on "MicroPython v1.22.2 on 2024-02-22; Generic ESP32 module with ESP32". import asyncio
import socket
import network
ssid = 'MicroPython-AP'
password = '123456789'
count = 1
async def connect_to_ap():
ap = network.WLAN(network.AP_IF)
ap.active(True)
ap.config(essid=ssid, authmode=3, password=password)
ap.ifconfig(('10.10.4.1', '255.255.255.0', '10.10.4.1', '1.1.1.1'))
while not ap.active():
await asyncio.sleep(1)
print('Connection successful')
print(ap.ifconfig())
async def handle_client(reader, writer):
global count
print(f'Handle #{count}')
request = await reader.readline()
print('Content =', request.decode('utf-8'))
response = web_page()
writer.write(response.encode('utf-8'))
await writer.drain()
writer.close()
print('Done!')
def web_page():
global count
html = f"""<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body><h1>#{count} Hello, World!</h1></body></html>"""
count+=1
return html
async def server():
server = await asyncio.start_server(handle_client, '0.0.0.0', 80)
print('Web server started')
await server.wait_closed()
async def main():
await connect_to_ap()
await server()
asyncio.run(main()) It works, hopefully it works for you too. Sometimes we just need a simple http server without the need for a full framework like microdot. |
Beta Was this translation helpful? Give feedback.
I need the ap.ifconfig(...) as my home router has the same IP as the default AP IP address. And it works for esp32. I need to recompile the RP2040 firmware to change the AP address, unfortunately this cannot be done from MP.
If you see
Handle #9
, then your browser request reached the server, but somehow the response never got back to the client.This change to web_page() will ensure that the response contains correctly formatted html.