03-16-2025, 05:55 PM
This is to create an access point with a webpage that serves a simple "hello world" using asyncio. I try to use asyncio whenever possible so I don't have blocking code stopping everything and causing timing issues.
This creates an asyncio access point with a static IP address. You can configure your own addressing scheme in the ap.config line.
Code:
import socket
import network
#import esp
import uasyncio as asyncio
import gc
#esp.osdebug(None)
gc.collect()
ssid = 'New AP'
password = '123456789'
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, authmode=network.AUTH_WPA_WPA2_PSK, password=password)
ap.active(True)
while not ap.active():
pass
print(('Access point started -'), ssid)
print(ap.ifconfig())
def web_page():
html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body><h1>Hello, World!</h1></body></html>"""
return html
async def handle_client(conn):
print('Got a connection')
request = await conn.recv(1024)
print('Content = %s' % str(request))
response = web_page()
conn.send(response)
conn.close()
async def main():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
asyncio.create_task(handle_client(conn))
# Run the main function
asyncio.run(main())
This creates an asyncio access point with a static IP address. You can configure your own addressing scheme in the ap.config line.
Code:
import socket
import network
import uasyncio as asyncio
ssid = 'Access Point'
password = 'password'
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, authmode=network.AUTH_WPA_WPA2_PSK, password=password)
# Static IP
ap.ifconfig(('192.168.100.205', '255.255.255.0', '192.168.100.2', '8.8.8.8'))
ap.active(True)
# Wait for WiFi to go active
async def wait_for_wifi():
wait_counter = 0
while not ap.active():
print("waiting " + str(wait_counter))
await asyncio.sleep(0.5)
wait_counter += 1
async def print_status():
await asyncio.sleep(1) # Give some time for the AP to be active
print('WiFi active')
status = ap.ifconfig()
print('subnet mask = ' + status[1])
print('gateway = ' + status[2])
print('DNS server = ' + status[3])
print('IP address = ' + status[0])
print('AP Name = ', (ssid))
def web_page():
html = """<html><head><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body><h1>Hello, World!</h1></body></html>"""
return html
async def handle_client(conn):
print('Got a connection')
request = await conn.recv(1024)
print('Content = %s' % str(request))
response = web_page()
conn.send(response)
conn.close()
async def main():
await wait_for_wifi()
await print_status()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 80))
s.listen(5)
while True:
conn, addr = s.accept()
print('Got a connection from %s' % str(addr))
asyncio.create_task(handle_client(conn))
# Run the main function
asyncio.run(main())