From 6156f87b059de402a8e93fe3b55f44bdd0f86a16 Mon Sep 17 00:00:00 2001 From: sickprodigy Date: Wed, 5 Nov 2025 16:25:06 -0500 Subject: [PATCH] Improve connect_wifi function for better error handling and connection logic --- Scripts/networking.py | 91 ++++++++++++++++++++++++++++--------------- 1 file changed, 60 insertions(+), 31 deletions(-) diff --git a/Scripts/networking.py b/Scripts/networking.py index a007bcf..6bfe54c 100644 --- a/Scripts/networking.py +++ b/Scripts/networking.py @@ -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 \ No newline at end of file + + 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 \ No newline at end of file