Change connect_wifi function to include max_retries and timeout parameters for improved connection handling and feedback

This commit is contained in:
Aaron 2025-11-05 16:27:05 -05:00
parent eb34922da6
commit 3dd565537f

View File

@ -2,24 +2,33 @@ import network
import time import time
from secrets import secrets from secrets import secrets
def connect_wifi(led=None): def connect_wifi(led=None, max_retries=3, timeout=20):
"""Connect to WiFi using credentials from secrets.py""" """
Connect to WiFi using credentials from secrets.py
Args:
led: Optional LED pin for visual feedback
max_retries: Number of connection attempts (default: 3)
timeout: Seconds to wait for connection per attempt (default: 20)
Returns:
WLAN object if connected, None if failed
"""
wlan = network.WLAN(network.STA_IF)
# Ensure clean state
try: try:
wlan = network.WLAN(network.STA_IF)
# Deactivate first if already active (fixes EPERM error)
if wlan.active(): if wlan.active():
wlan.active(False) wlan.active(False)
time.sleep(1) time.sleep(1)
wlan.active(True) wlan.active(True)
time.sleep(1) # Give it time to initialize time.sleep(1)
except OSError as e: except OSError as e:
print(f"WiFi activation error: {e}") print(f"WiFi activation error: {e}")
print("Attempting reset...") print("Attempting reset...")
try: try:
# Force deinit and reinit
wlan.deinit() wlan.deinit()
time.sleep(2) time.sleep(2)
wlan = network.WLAN(network.STA_IF) wlan = network.WLAN(network.STA_IF)
@ -29,38 +38,69 @@ def connect_wifi(led=None):
print(f"WiFi reset failed: {e2}") print(f"WiFi reset failed: {e2}")
return None return None
if not wlan.isconnected(): # Try connecting with retries
print('Connecting to WiFi...') for attempt in range(1, max_retries + 1):
if wlan.isconnected():
print(f"Already connected to WiFi")
break
print(f'Connecting to WiFi (attempt {attempt}/{max_retries})...')
try: try:
wlan.connect(secrets['ssid'], secrets['password']) wlan.connect(secrets['ssid'], secrets['password'])
except Exception as e: except Exception as e:
print(f"Connection attempt failed: {e}") print(f"Connection attempt failed: {e}")
return None if attempt < max_retries:
print("Retrying in 3 seconds...")
time.sleep(3)
continue
# Wait for connection with timeout # Wait for connection with timeout
max_wait = 20 wait_time = 0
while max_wait > 0: while wait_time < timeout:
if wlan.isconnected(): if wlan.isconnected():
break break
if led: if led:
led.toggle() led.toggle()
time.sleep(0.5) time.sleep(0.5)
max_wait -= 1 wait_time += 0.5
print('.', end='')
# Print progress dots every 2 seconds
if int(wait_time * 2) % 4 == 0:
print('.', end='')
print() print() # New line after dots
if not wlan.isconnected(): if wlan.isconnected():
print('WiFi connection failed!') break
if led:
led.off() print(f'Connection attempt {attempt} failed')
return None if attempt < max_retries:
print("Retrying in 3 seconds...")
time.sleep(3)
# Final connection check
if not wlan.isconnected():
print('WiFi connection failed after all attempts!')
if led:
led.off()
return None
# Success feedback
if led: if led:
# Single pulse on successful connection # Double pulse on successful connection
led.on() for _ in range(2):
time.sleep(0.5) led.on()
led.off() time.sleep(0.2)
led.off()
time.sleep(0.2)
print('Connected to WiFi successfully!')
# Print connection details
ifconfig = wlan.ifconfig()
print(f"IP: {ifconfig[0]} | Gateway: {ifconfig[2]}")
print('Connected to WiFi')
return wlan return wlan