import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# --- CONFIGURACIÓN MQTT ---
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "test.mosquitto.org" # Broker público alternativo
MQTT_PORT = 8080 # WebSocket port
MQTT_TOPIC = "wokwi-weather"
sensor = dht.DHT22(Pin(15))
# --- CONEXIÓN WI-FI ---
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
time.sleep(0.1)
print("Connected to WiFi!")
# --- CONEXIÓN MQTT ---
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, port=MQTT_PORT)
client.connect()
print("Connected to MQTT broker!")
prev_weather = ""
while True:
sensor.measure()
message = ujson.dumps({
"temp": sensor.temperature(),
"humidity": sensor.humidity()
})
if message != prev_weather:
client.publish(MQTT_TOPIC, message)
prev_weather = message
time.sleep(1)