import network
import urequests
import time
from machine import Pin
# ── Configuração dos LEDs ────────────────────────────────────────────────────
led_L1 = Pin(10, Pin.OUT)
led_L2 = Pin(11, Pin.OUT)
# Mapa: chave do JSON → objeto Pin
LEDS = {
"L1": led_L1,
"L2": led_L2,
}
# ── Endpoint ─────────────────────────────────────────────────────────────────
URL = "https://kipson.pythonanywhere.com/micro"
# ── Conexão WiFi ─────────────────────────────────────────────────────────────
def conectar_wifi(ssid: str, senha: str) -> None:
"""Conecta ao WiFi e aguarda até obter endereço IP."""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, senha)
print(f"\nConectando à rede '{ssid}'", end="")
while not wlan.isconnected():
print(".", end="")
time.sleep(0.5)
ip = wlan.ifconfig()[0]
print(f"\nConectado! Endereço IP: {ip}\n")
# ── Controle de LEDs ──────────────────────────────────────────────────────────
def aplicar_status(equip: str, status: int) -> None:
"""Liga ou desliga o LED correspondente ao equipamento."""
led = LEDS.get(equip)
if led is None:
print(f" [AVISO] Equipamento desconhecido: '{equip}' — ignorado.")
return
if status == 1:
led.value(1)
print(f" Dispositivo {equip}: LIGADA → LED ON")
else:
led.value(0)
print(f" Dispositivo {equip}: DESLIGADA → LED OFF")
# ── Consulta HTTP ─────────────────────────────────────────────────────────────
def consultar_endpoint() -> None:
"""Faz GET no endpoint e processa a lista de dispositivos."""
try:
resposta = urequests.get(URL, timeout=5)
dados = resposta.json() # {"dispositivos": [{equip: status}, ...]}
resposta.close()
equipamentos = dados.get("dispositivos", [])
print(f"[{time.ticks_ms() // 1000}s] {len(equipamentos)} dispositivo(s) recebido(s):")
for item in equipamentos:
for equip, status in item.items():
aplicar_status(equip, status)
except OSError as e:
print(f" [ERRO de rede] {e}")
except ValueError as e:
print(f" [ERRO ao decodificar JSON] {e}")
except Exception as e:
print(f" [ERRO inesperado] {e}")
# ── Programa principal ────────────────────────────────────────────────────────
def main() -> None:
conectar_wifi(ssid="Wokwi-GUEST", senha="")
print("Iniciando loop de monitoramento (intervalo: 1 s)...\n")
while True:
consultar_endpoint()
time.sleep(1)
main()
Loading
pi-pico-w
pi-pico-w