Last active
July 30, 2024 17:17
-
-
Save skittleson/05d82364af759ee5d1289dd67023cb69 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import network | |
import socket | |
import time | |
# Step 1: Set Up AP Mode | |
def access_point(ssid, password = None): | |
import network | |
wlan = network.WLAN(network.AP_IF) | |
wlan.config(essid=ssid) | |
if password: | |
wlan.config(password=password) | |
else: | |
wlan.config(security=0) # disable password | |
wlan.active(True) | |
return wlan | |
# Step 3: Update the Web Page with Datalist | |
def generate_html(): | |
html = f"""<!DOCTYPE html> | |
<html> | |
<head> | |
<title>WiFi Captive Portal</title> | |
</head> | |
<body> | |
<h2>Select WiFi Network</h2> | |
<form action="/configure" method="GET"> | |
<label for="ssid">SSID:</label><br> | |
<input id="ssid" name="ssid"><br> | |
<label for="password">Password:</label><br> | |
<input type="password" id="password" name="password"><br><br> | |
<input type="submit" value="Connect"> | |
</form> | |
</body> | |
</html> | |
""" | |
return html | |
def parse_params(url): | |
params = {} | |
if '?' in url: | |
url_parts = url.split('?', 1) | |
param_str = url_parts[1] | |
param_pairs = param_str.split('&') | |
for pair in param_pairs: | |
key, value = pair.split('=') | |
params[key] = value | |
return params | |
# Step 4: Create and Start the Web Server | |
def start_server(): | |
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1] | |
s = socket.socket() | |
s.bind(addr) | |
s.listen(1) | |
print('Web server started on 0.0.0.0:80') | |
while True: | |
cl, addr = s.accept() | |
print('Client connected from', addr) | |
request = cl.recv(1024) | |
request = str(request) | |
print('Request:', request) | |
if 'GET /configure?' in request: | |
url = request.split(' ')[1] | |
params = parse_params(url) | |
ssid = params.get('ssid', '').replace('%20', ' ') | |
password = params.get('password', '').replace('%20', ' ') | |
print('SSID:', ssid) | |
print('Password:', password) | |
connect_to_wifi(ssid, password) | |
response = 'HTTP/1.1 200 OK\n\n' + 'Connecting to WiFi...' | |
else: | |
response = 'HTTP/1.1 200 OK\n\n' + generate_html() | |
cl.send(response) | |
cl.close() | |
def connect_to_wifi(ssid, password): | |
sta_if = network.WLAN(network.STA_IF) | |
sta_if.active(True) | |
sta_if.connect(ssid, password) | |
while not sta_if.isconnected(): | |
print('Trying to connect...') | |
time.sleep(1) | |
print('Connected to', ssid) | |
print('Network config:', sta_if.ifconfig()) | |
ap = access_point('picow') | |
print('IP Address To Connect to:: ' + ap.ifconfig()[0]) | |
start_server() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment