Improve connect_wifi function for better error handling and connection logic

This commit is contained in:
2025-11-05 16:25:06 -05:00
parent e82fcf46aa
commit 6156f87b05

View File

@@ -2,36 +2,65 @@ import network
import time
from secrets import secrets
RECONNECT_COOLDOWN_MS = 60000 # 60 seconds
def connect_wifi(led=None, timeout=10):
"""
Connect to WiFi using secrets['ssid'] / secrets['password'].
If `led` (machine.Pin) is provided, pulse it once on successful connect.
Returns the WLAN object or None on failure.
"""
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
# print("Connecting to WiFi...", end="")
wifi.connect(secrets['ssid'], secrets['password'])
# Wait for connection with timeout
max_wait = timeout
while max_wait > 0:
if wifi.status() < 0 or wifi.status() >= 3:
break
max_wait -= 1
# print(".", end="")
time.sleep(1)
def connect_wifi(led=None):
"""Connect to WiFi using credentials from secrets.py"""
try:
wlan = network.WLAN(network.STA_IF)
if wifi.isconnected():
# print("\nConnected! Network config:", wifi.ifconfig())
if led:
led.on()
# Deactivate first if already active (fixes EPERM error)
if wlan.active():
wlan.active(False)
time.sleep(1)
led.off()
return wifi
else:
# print("\nConnection failed!")
return None
wlan.active(True)
time.sleep(1) # Give it time to initialize
except OSError as e:
print(f"WiFi activation error: {e}")
print("Attempting reset...")
try:
# Force deinit and reinit
wlan.deinit()
time.sleep(2)
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
time.sleep(1)
except Exception as e2:
print(f"WiFi reset failed: {e2}")
return None
if not wlan.isconnected():
print('Connecting to WiFi...')
try:
wlan.connect(secrets['ssid'], secrets['password'])
except Exception as e:
print(f"Connection attempt failed: {e}")
return None
# Wait for connection with timeout
max_wait = 20
while max_wait > 0:
if wlan.isconnected():
break
if led:
led.toggle()
time.sleep(0.5)
max_wait -= 1
print('.', end='')
print()
if not wlan.isconnected():
print('WiFi connection failed!')
if led:
led.off()
return None
if led:
# Single pulse on successful connection
led.on()
time.sleep(0.5)
led.off()
print('Connected to WiFi')
return wlan