Improve connect_wifi function for better error handling and connection logic
This commit is contained in:
@@ -2,36 +2,65 @@ import network
|
||||
import time
|
||||
from secrets import secrets
|
||||
|
||||
RECONNECT_COOLDOWN_MS = 60000 # 60 seconds
|
||||
def connect_wifi(led=None):
|
||||
"""Connect to WiFi using credentials from secrets.py"""
|
||||
try:
|
||||
wlan = network.WLAN(network.STA_IF)
|
||||
|
||||
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)
|
||||
# Deactivate first if already active (fixes EPERM error)
|
||||
if wlan.active():
|
||||
wlan.active(False)
|
||||
time.sleep(1)
|
||||
|
||||
# print("Connecting to WiFi...", end="")
|
||||
wifi.connect(secrets['ssid'], secrets['password'])
|
||||
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 = timeout
|
||||
max_wait = 20
|
||||
while max_wait > 0:
|
||||
if wifi.status() < 0 or wifi.status() >= 3:
|
||||
if wlan.isconnected():
|
||||
break
|
||||
max_wait -= 1
|
||||
# print(".", end="")
|
||||
time.sleep(1)
|
||||
|
||||
if wifi.isconnected():
|
||||
# print("\nConnected! Network config:", wifi.ifconfig())
|
||||
if led:
|
||||
led.on()
|
||||
time.sleep(1)
|
||||
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 wifi
|
||||
else:
|
||||
# print("\nConnection failed!")
|
||||
return None
|
||||
|
||||
if led:
|
||||
# Single pulse on successful connection
|
||||
led.on()
|
||||
time.sleep(0.5)
|
||||
led.off()
|
||||
|
||||
print('Connected to WiFi')
|
||||
return wlan
|
||||
Reference in New Issue
Block a user