import network, time, urequests
from machine import Pin
from utime import sleep, sleep_ms
from umqtt.simple import MQTTClient
import ujson
sala = Pin(18, Pin.OUT)
puerta = Pin(15, Pin.OUT)
# MQTT Server Parameters
MQTT_CLIENT_ID = "Hugo243535Unico21" # UNICO random
MQTT_BROKER = "test.mosquitto.org"
MQTT_USER = ""
MQTT_PASSWORD = ""
MQTT_TOPIC_SUB = "datos/profe/recibe"
def conectaWifi (red, password):
global miRed
miRed = network.WLAN(network.STA_IF)
if not miRed.isconnected(): #Si no está conectado…
miRed.active(True) #activa la interface
miRed.connect(red, password) #Intenta conectar con la red
print('Conectando a la red', red +"…")
timeout = time.time ()
while not miRed.isconnected(): #Mientras no se conecte..
if (time.ticks_diff (time.time (), timeout) > 10):
return False
return True
if conectaWifi ("Wokwi-GUEST", ""):
print ("Conexión exitosa!")
print('Datos de la red (IP/netmask/gw/DNS):', miRed.ifconfig())
print("Conectando a MQTT server... ",MQTT_BROKER,"...", end="")
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER, user=MQTT_USER, password=MQTT_PASSWORD)
client.connect()
def sub_cb(topic, msg):
recibe = ujson.loads(msg.decode())
print(f'Recibido:{recibe}')
print(recibe["Valor"])
r = recibe["Valor"]
if r == 0:
sala.off()
elif r == 1:
sala.on()
elif r == 2:
puerta.on()
elif r == 3:
puerta.off()
while True:
client.set_callback(sub_cb)
client.subscribe(MQTT_TOPIC_SUB)
print ("...esperando")
client.wait_msg()
sleep(2)
else:
print ("Imposible conectar")
miRed.active (False)