Files
led-driver/src/wifi_sta.py
T
jimmyandCursor 55a97ac51c feat(patterns): merge pattern styles and add mode support
Consolidate legacy pattern ids into meteor, particles, sparkle, chase,
and colour_cycle with n6/mode style selection; add pattern_modes helper,
self-contained tests/all.py, and preset mode alias on wire.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-16 21:14:54 +12:00

130 lines
4.1 KiB
Python

"""STA connect helpers aligned with tests/test_wifi.py (status polling, fatal codes)."""
import gc
import machine
import utime
import network
_CONNECT_TIMEOUT_S = 45
_RETRY_DELAY_S = 2
def _wifi_status_label(code):
names = {
getattr(network, "STAT_IDLE", 0): "idle",
getattr(network, "STAT_CONNECTING", 1): "connecting",
getattr(network, "STAT_WRONG_PASSWORD", -3): "wrong_password",
getattr(network, "STAT_NO_AP_FOUND", -2): "no_ap_found",
getattr(network, "STAT_CONNECT_FAIL", -1): "connect_fail",
getattr(network, "STAT_GOT_IP", 3): "got_ip",
}
return names.get(code, str(code))
# Only abort the wait loop immediately on wrong password. NO_AP_FOUND / CONNECT_FAIL are often
# transient while the radio is still scanning (ESP32-C3 may report them before the AP appears).
_ABORT_WAIT_IMMEDIATE = (
getattr(network, "STAT_WRONG_PASSWORD", -3),
)
def _one_association_campaign(sta_if, ssid, password, wdt):
"""disconnect → connect → wait until connected, wrong password, or timeout. Returns True if connected."""
try:
sta_if.disconnect()
except Exception:
pass
utime.sleep_ms(200)
try:
sta_if.connect(ssid, password)
except Exception as ex:
print("wifi_sta: connect raised:", ex)
return False
start = utime.time()
last_status = None
while not sta_if.isconnected():
status = sta_if.status()
if status != last_status:
print("wifi_sta: status", status, _wifi_status_label(status))
last_status = status
if status in _ABORT_WAIT_IMMEDIATE:
return False
if utime.time() - start >= _CONNECT_TIMEOUT_S:
print("wifi_sta: association timeout")
return False
utime.sleep(1)
if wdt is not None:
wdt.feed()
return True
def boot_sta(settings, wdt):
"""Tear down and bring up STA. Call before large heap users (NeoPixel, patterns).
On ESP32-C3, soft reboots can leave the Wi-Fi driver allocated; init while the
heap is still free. If re-init fails after a soft reboot, hard-reset once.
"""
sta_if = network.WLAN(network.STA_IF)
try:
if sta_if.active():
try:
sta_if.disconnect()
except Exception:
pass
sta_if.active(False)
except Exception:
pass
utime.sleep_ms(100)
gc.collect()
try:
sta_if.active(True)
except OSError as e:
err = str(e)
if "Out of Memory" in err or "WiFi" in err:
if machine.reset_cause() == machine.SOFT_RESET:
print("wifi_sta: init failed after soft reboot, hard reset:", err)
machine.reset()
raise
sta_if.config(pm=network.WLAN.PM_NONE)
ssid = settings.get("ssid") or ""
if ssid:
connect_until_up(sta_if, ssid, settings.get("password") or "", wdt)
return sta_if
def connect_until_up(sta_if, ssid, password, wdt):
"""Boot: repeat campaigns until STA has a route (same strategy as tests/test_wifi.py)."""
if not ssid:
print("wifi_sta: no ssid in settings")
return False
attempt = 0
while True:
attempt += 1
print("wifi_sta: boot attempt", attempt, "ssid=", repr(ssid))
if _one_association_campaign(sta_if, ssid, password, wdt):
try:
print("wifi_sta: connected", sta_if.ifconfig()[0])
except Exception:
print("wifi_sta: connected")
return True
print("wifi_sta: retry in", _RETRY_DELAY_S, "s")
for _ in range(_RETRY_DELAY_S):
utime.sleep(1)
if wdt is not None:
wdt.feed()
def try_reconnect(sta_if, ssid, password, wdt):
"""Runtime: single association campaign after link loss; non-looping."""
if not ssid:
return False
print("wifi_sta: reconnect")
ok = _one_association_campaign(sta_if, ssid, password, wdt)
if ok:
try:
print("wifi_sta: connected", sta_if.ifconfig()[0])
except Exception:
print("wifi_sta: connected")
return ok