Monday, February 22, 2021

ESP32/MicroPython exercise: act as Access Point, and setup a simple web server


With MicroPython installed on ESP32 (ESP32-DevKitC V4), it's a exercise to act as Access Point, and setup a simple web server.


upyESP32_AP_WebSvr_20210223a.py
import uos
import network
import usocket
"""
ESP32/MicroPython exercise:
ESP32 act as Access Point,
and setup a simple web server

ref:
MicroPython usocket – socket module
https://docs.micropython.org/en/latest/library/usocket.html
"""

ssid= "ESP32-ssid"
password="password"

print("----- MicroPython -----")
for u in uos.uname():
    print(u)
print("-----------------------")

ap = network.WLAN(network.AP_IF) # Access Point
ap.config(essid=ssid,password=password,authmode=network.AUTH_WPA_WPA2_PSK) 
ap.config(max_clients=1)  # max number of client
ap.active(True)           # activate the access point

print(ap.ifconfig())
print(dir(ap))

def get_html(fromip):
    html_head="""<HTML><HEAD>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        </HEAD>
        <BODY><b>Hello ESP32/MicroPython</b><br/>"""
    html_end="""</BODY>
        </HTML>"""
    html=html_head+"your ip: "+fromip+html_end
    return html


mysocket = usocket.socket(usocket.AF_INET, usocket.SOCK_STREAM)
mysocket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)

mysocket.bind(('', 80))
mysocket.listen(1)

while True:
  conn, addr = mysocket.accept()
  print('Connected from: %s' % str(addr))
  print()
  request = conn.recv(1024)
  print('request: %s' % str(request))
  print()
  conn.send(get_html(addr[0]))
  conn.close()



OSError: [Errno 98] EADDRINUSE

 It can be noticed that I have the  following code before mysocket.bind():
mysocket.setsockopt(usocket.SOL_SOCKET, usocket.SO_REUSEADDR, 1)
Without this code, error of "OSError: [Errno 98] EADDRINUSE" will be thrown sometimes; such as Run the program > client connect and load the web page > then re-start the program.

This code fix it in my case.


Next:

No comments: