Refactor WiFi connection logic and clean up commented code

This commit is contained in:
Aaron 2025-11-03 19:37:08 -05:00
parent 2767f206a7
commit c3779ee4a4

63
main.py
View File

@ -4,44 +4,51 @@ import network
import urequests as requests import urequests as requests
from secrets import secrets from secrets import secrets
# Load login data from different file for security!
# ssid = secrets['ssid']
# pw = secrets['password']
# Initialize pins # Initialize pins
contactorLights = Pin(18, Pin.OUT) contactorLights = Pin(18, Pin.OUT)
led = machine.Pin("LED", machine.Pin.OUT) led = Pin("LED", Pin.OUT)
# Initial state
led.low() led.low()
contactorLights.low() # sets to lowest setting 0 first. contactorLights.low()
contactorLights.toggle() # Toggle contactor on for testing # Network connection
def connect_wifi():
wifi = network.WLAN(network.STA_IF)
wifi.active(True)
# Network connection going through print("Connecting to WiFi...", end="")
wifi = network.WLAN(network.STA_IF) wifi.connect(secrets['ssid'], secrets['password'])
wifi.active(True) # must capitalize boolean statements!
wifi.connect(secrets['ssid'], secrets['password'])
print(wifi.ifconfig()) # no ip being applied # Wait for connection with timeout
max_wait = 10
while max_wait > 0:
if wifi.status() < 0 or wifi.status() >= 3:
break
max_wait -= 1
print(".", end="")
time.sleep(1)
#Proof connected if wifi.isconnected():
led.on() print("\nConnected! Network config:", wifi.ifconfig())
print('Connected to Wi-Fi network') # saying connected but not led.on()
time.sleep(5) time.sleep(1)
led.off() led.off()
return wifi
else:
print("\nConnection failed!")
return None
# If disconnect will flash light # Connect to WiFi
while wifi.isconnected() == False: wifi = connect_wifi()
# Connection monitoring loop
while True:
if not wifi or not wifi.isconnected():
led.on() led.on()
time.sleep(0.5) time.sleep(0.5)
led.off() led.off()
time.sleep(0.5) time.sleep(0.5)
# Try to reconnect
# think the while loop will hold the next line from running, we will see wifi = connect_wifi()
time.sleep(1)
# while True:
# led.toggle()
# utime.sleep(0.2)
# Need to log time accurately. Connect to internet with wifi and set time. Start logging. Also need temp probes and how to pull temps